C++ <mutex>
系统讲解 <mutex> 四类互斥量(mutex/recursive_mutex/timed_mutex/recursive_timed_mutex)、RAII 锁封装器(lock_guard/unique_lock)及 adopt/defer/try_to_lock 策略标记,并在离线 G++ C++17 环境真实验证。
学完这一章,你能够
- 系统讲解 <mutex> 四类互斥量(mutex/recursive_mutex/timed_mutex/recursive_timed_mutex)、RAII 锁封装器(lock_guard/unique_lock)及 adopt/defer/try_to_lock 策略标记,并在离线 G++ C++17 环境真实验证。
互斥锁同步模型与四类标准互斥量
多线程并发读写同一共享变量时必须借助互斥同步避免数据竞争。C++11 `<mutex>` 头文件提供了四种标准互斥量类型:`std::mutex` 是最基础的独占非递归互斥锁;`std::recursive_mutex` 允许**同一个线程**多次嵌套加锁(需对应相同次数的解锁);`std::timed_mutex` 额外支持带相对超时(`try_lock_for`)和绝对截止时间(`try_lock_until`)的限时抢锁;`std::recursive_timed_mutex` 则同时具备同一线程重入与限时抢锁两种能力(注:标准中它与 `std::timed_mutex` 是各自独立的类,并非继承关系)。
基础互斥、递归互斥实战与计数细节
在双线程共享计数器示例中,两个线程分别循环 `10000` 次对 `shared_resource` 加 1;凭借互斥锁保证每次自增的读-改-写成为临界区内的原子步骤,最终结果确定等于 `20000`(无锁保护则会因指令交错丢失更新)。
当递归函数内部需要持有互斥锁并再次调用自身时,普通 `std::mutex` 会在同线程第二次加锁时发生自死锁,此时应改用 `std::recursive_mutex`。在 `recursive_increment(int count)` 示例中,终止条件为 `if (count <= 0) return;`,每层递归用 `std::lock_guard<std::recursive_mutex>` 锁定 `rmtx` 后执行 `++shared_resource` 再调用 `recursive_increment(count - 1)`。两个线程分别调用 `recursive_increment(3)`,各自实际执行 `count = 3, 2, 1` 共 3 次递增,总计精确为 `6`(注意 `count == 0` 在入口即返回,不执行递增)。
工程实践应严格遵守三项守则:每次加锁都必须保证在所有返回与异常路径上解锁;优先使用 RAII 封装器 `std::lock_guard` 或 `std::unique_lock` 代替手工调用 `lock()`/`unlock()`,防止异常抛出跳过解锁而引发永久死锁;尽量缩小临界区范围,避免持锁期间执行耗时或未知回调。
限时互斥量、锁管理器与锁定策略标记详解
对于不能无限期阻塞的实时或防死锁场景,可对 `std::timed_mutex` 或 `std::recursive_timed_mutex` 调用 `try_lock_for(std::chrono::milliseconds(...))`:在超时窗口内成功抢占返回 `true`(用完后须 `unlock()`),超时仍未获得则返回 `false` 供业务走降级路径。
在锁管理器层面:`std::lock_guard` 构造即锁、析构即解,零额外状态开销;`std::unique_lock` 则允许中途手动 `unlock()`/`lock()`、移动所有权以及配合条件变量使用(**重要澄清**:仅当 `unique_lock` 包装的是 `std::timed_mutex` 等满足 `TimedLockable` 的互斥量时,才能调用 `lock.try_lock_for(...)`,对普通 `std::mutex` 实例化调用 `try_lock_for` 无法通过编译)。`std::unique_lock` 还支持三种策略标记:`std::adopt_lock`(标记类型 `std::adopt_lock_t`)接管当前线程**已经提前锁定**的互斥量;`std::defer_lock`(`std::defer_lock_t`)延迟锁定,构造时暂不加锁以便后续统一 `std::lock()` 或按需加锁;`std::try_to_lock`(`std::try_to_lock_t`)尝试非阻塞加锁,可通过 `if (lock1 && lock2)` 检查是否同时获得。本站已在离线 Docker G++ C++17 环境完整实测上述全部互斥量、锁管理器与策略标记。
实测 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;
}
- 确认双线程 2x10000 互斥递增为 20000、双线程 3 层递归递增精确为 6、timed_mutex 持锁超时 false 且释放后 true、recursive_timed_mutex 重入成功,以及 unique_lock 手动解重锁与 adopt/defer/try_to_lock 全部通过。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:11dd7f791221af4f91649366c851634dd67fd132630826121668e1c700964eec
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:425e2082d1c82bda570fed18e4bfdd7e66c62da7fae09407c4da0f41012ae282
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
构造 `std::unique_lock<std::mutex> lk(mtx, std::adopt_lock);` 之前必须满足什么前提条件?若不满足会怎样?
展开参考解答
当前线程必须在构造 `lk` 之前已经锁定了 `mtx`(例如先调用过 `mtx.lock()` 或 `std::lock(mtx, ...)`),`adopt_lock` 仅移交解锁职责而不再加锁;若对未锁定的互斥量使用 `adopt_lock`,会导致未定义行为。