std::lock_guard
STD::锁[医]护卫
Defined in header | | |
---|---|---|
template< class Mutex > class lock_guard; | | |
全班lock_guard
是一个互斥包装器,它提供了一个方便的雷伊式在作用域块的持续时间内拥有互斥的机制。
当lock_guard
对象,它尝试获取给定的互斥对象的所有权。控件离开lock_guard
对象的lock_guard
会被破坏,互斥被释放。
大lock_guard
课堂是不可复制的。
模板参数
Mutex | - | the type of the mutex to lock. The type must meet the BasicLockable requirements |
---|
成员类型
Member type | Definition |
---|---|
mutex_type | Mutex |
成员函数
(constructor) | constructs a lock_guard, optionally locking the given mutex (public member function) |
---|---|
(destructor) | destructs the lock_guard object, unlocks the underlying mutex (public member function) |
operator= deleted | not copy-assignable (public member function) |
例
二次
#include <thread>
#include <mutex>
#include <iostream>
int g_i = 0;
std::mutex g_i_mutex; // protects g_i
void safe_increment()
{
std::lock_guard<std::mutex> lock(g_i_mutex
++g_i;
std::cout << std::this_thread::get_id() << ": " << g_i << '\n';
// g_i_mutex is automatically released when lock
// goes out of scope
}
int main()
{
std::cout << __func__ << ": " << g_i << '\n';
std::thread t1(safe_increment
std::thread t2(safe_increment
t1.join(
t2.join(
std::cout << __func__ << ": " << g_i << '\n';
}
二次
可能的产出:
二次
main: 0
140641306900224: 1
140641298507520: 2
main: 2
二次
另见
unique_lock (C++11) | implements movable mutex ownership wrapper (class template) |
---|---|
scoped_lock (C++17) | deadlock-avoiding RAII wrapper for multiple mutexes (class template) |
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。