在线代码实验室
实测 std::mutex/recursive_mutex/timed_mutex/recursive_timed_mutex 与 unique_lock 三种策略标记
#include <chrono>
#include <cstdio>
#include <future>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
static std::recursive_mutex g_rmtx;
static int g_rec_shared = 0;
static void recursive_increment(int count) {
if (count <= 0) return;
std::lock_guard<std::recursive_mutex> lock(g_rmtx);
++g_rec_shared;
recursive_increment(count - 1);
}
int main() {
std::vector<lab::Case> cases;
// Case 1: std::mutex + std::lock_guard protecting 2x10000 increments
std::mutex mtx;
int shared_resource = 0;
auto inc = [&]() {
for (int i = 0; i < 10000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
++shared_resource;
}
};
std::thread t1(inc);
std::thread t2(inc);
t1.join();
t2.join();
cases.push_back({
"mutex_basic_and_lock_guard",
std::to_string(20000),
std::to_string(shared_resource),
shared_resource == 20000
});
// Case 2: std::recursive_mutex with 2 threads x depth 3 == 6
g_rec_shared = 0;
std::thread r1(recursive_increment, 3);
std::thread r2(recursive_increment, 3);
r1.join();
r2.join();
cases.push_back({
"mutex_recursive_increment",
std::to_string(6),
std::to_string(g_rec_shared),
g_rec_shared == 6
});
// Case 3: std::timed_mutex timeout + acquisition & std::recursive_timed_mutex reentrant try_lock_for
std::timed_mutex tmtx;
std::promise<void> locked_prom;
auto locked_fut = locked_prom.get_future();
std::promise<void> release_prom;
auto release_fut = release_prom.get_future();
std::thread holder([&]() {
tmtx.lock();
locked_prom.set_value();
release_fut.wait();
tmtx.unlock();
});
locked_fut.wait();
bool while_held = tmtx.try_lock_for(std::chrono::milliseconds(15));
release_prom.set_value();
holder.join();
bool after_release = tmtx.try_lock_for(std::chrono::milliseconds(50));
if (after_release) tmtx.unlock();
std::recursive_timed_mutex rtm;
bool rtm1 = rtm.try_lock_for(std::chrono::milliseconds(20));
bool rtm2 = rtm.try_lock_for(std::chrono::milliseconds(20));
if (rtm2) rtm.unlock();
if (rtm1) rtm.unlock();
bool ok3 = (!while_held) && after_release && rtm1 && rtm2;
cases.push_back({
"mutex_timed_and_recursive_timed",
lab::jbool(true),
lab::jbool(ok3),
ok3
});
// Case 4: unique_lock manual unlock/relock + adopt_lock, defer_lock, try_to_lock
std::mutex m1, m2;
std::unique_lock<std::mutex> ul(m1);
bool own1 = ul.owns_lock();
ul.unlock();
bool own2 = ul.owns_lock();
ul.lock();
bool own3 = ul.owns_lock();
ul.unlock();
m1.lock();
bool adopt_ok = false;
{
std::unique_lock<std::mutex> adopt_lk(m1, std::adopt_lock);
adopt_ok = adopt_lk.owns_lock();
} // unlocks m1
std::unique_lock<std::mutex> defer_lk(m1, std::defer_lock);
bool defer_initial = defer_lk.owns_lock();
defer_lk.lock();
bool defer_after = defer_lk.owns_lock();
defer_lk.unlock();
std::unique_lock<std::mutex> try1(m1, std::try_to_lock);
std::unique_lock<std::mutex> try2(m2, std::try_to_lock);
bool try_both = static_cast<bool>(try1) && static_cast<bool>(try2);
bool ok4 = own1 && !own2 && own3 && adopt_ok && !defer_initial && defer_after && try_both;
cases.push_back({
"mutex_unique_lock_and_tag_types",
lab::jbool(true),
lab::jbool(ok4),
ok4
});
lab::emit(cases);
return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
入口文件:projects/cplusplus-cpp-libs-mutex-lab/explore-cpp-libs-mutex.cpp
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cpp-libs-mutex.cpp,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2359.zip