std::lock_guard
来自 cppreference.cn
定义于头文件 <mutex> |
||
template< class Mutex > class lock_guard; |
(C++11 起) | |
类lock_guard
是一个互斥体封装器,它提供了一个方便的RAII风格机制,用于在作用域块的持续时间内拥有一个互斥体。
当一个lock_guard
对象被创建时,它会尝试获取它被赋予的互斥体的所有权。当控制离开创建lock_guard
对象的作用域时,lock_guard
会被销毁,互斥体也会被释放。
lock_guard
类不可复制。
目录 |
[编辑] 模板参数
Mutex | - | 要锁定的互斥体类型。该类型必须满足BasicLockable要求 |
[编辑] 成员类型
成员类型 | 定义 |
mutex_type
|
Mutex |
[编辑] 成员函数
构造一个lock_guard ,可选地锁定给定的互斥体(公共成员函数) | |
销毁lock_guard 对象,解锁底层互斥体(公共成员函数) | |
operator= [已删除] |
不可复制赋值 (公共成员函数) |
[编辑] 注意
一个常见的初学者错误是“忘记”给lock_guard
变量命名,例如std::lock_guard(mtx);(它默认构造一个名为mtx
的lock_guard
变量)或std::lock_guard{mtx};(它构造一个prvalue对象,该对象立即被销毁),从而实际上没有构造一个在作用域剩余时间内持有互斥体的锁。
std::scoped_lock 为 |
(C++17 起) |
[编辑] 示例
演示了两个线程对 volatile 变量的安全和不安全增量。
运行此代码
#include <iostream> #include <mutex> #include <string_view> #include <syncstream> #include <thread> volatile int g_i = 0; std::mutex g_i_mutex; // protects g_i void safe_increment(int iterations) { const std::lock_guard<std::mutex> lock(g_i_mutex); while (iterations-- > 0) g_i = g_i + 1; std::cout << "thread #" << std::this_thread::get_id() << ", g_i: " << g_i << '\n'; // g_i_mutex is automatically released when lock goes out of scope } void unsafe_increment(int iterations) { while (iterations-- > 0) g_i = g_i + 1; std::osyncstream(std::cout) << "thread #" << std::this_thread::get_id() << ", g_i: " << g_i << '\n'; } int main() { auto test = [](std::string_view fun_name, auto fun) { g_i = 0; std::cout << fun_name << ":\nbefore, g_i: " << g_i << '\n'; { std::jthread t1(fun, 1'000'000); std::jthread t2(fun, 1'000'000); } std::cout << "after, g_i: " << g_i << "\n\n"; }; test("safe_increment", safe_increment); test("unsafe_increment", unsafe_increment); }
可能的输出
safe_increment: before, g_i: 0 thread #140121493231360, g_i: 1000000 thread #140121484838656, g_i: 2000000 after, g_i: 2000000 unsafe_increment: before, g_i: 0 thread #140121484838656, g_i: 1028945 thread #140121493231360, g_i: 1034337 after, g_i: 1034337
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 2981 | C++17 | 提供了冗余的从 lock_guard<Mutex> 推导指南 |
已移除 |
[编辑] 另请参阅
(C++11) |
实现可移动的互斥体所有权包装器 (类模板) |
(C++17) |
用于多个互斥体的死锁避免 RAII 包装器 (类模板) |