std::scoped_lock
STD:范围[医]锁
Defined in header | | |
---|---|---|
template< class... MutexTypes > class scoped_lock; | | (since C++17) |
全班scoped_lock
是一个互斥包装器,它提供了一个方便的雷伊式在作用域块的持续时间内拥有一个或多个互斥的机制。
当scoped_lock
对象,它尝试获取给定的互斥对象的所有权。控件离开scoped_lock
对象的scoped_lock
被破坏,互斥被释放,顺序相反。如果给定多个互斥项,则将死锁避免算法用作std::lock
...
大scoped_lock
课堂是不可复制的。
模板参数
MutexTypes | - | the types of the mutexes to lock. The types must meet the Lockable requirements unless sizeof...(MutexTypes)==1, in which case the only type must meet BasicLockable |
---|
成员类型
Member type | Definition |
---|---|
mutex_type | Mutex |
成员函数
(constructor) | constructs a scoped_lock, optionally locking the given mutexes (public member function) |
---|---|
(destructor) | destructs the scoped_lock object, unlocks the underlying mutexes (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::scoped_lock 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) |
---|
lock_guard (C++11) | implements a strictly scope-based mutex ownership wrapper (class template) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。