首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::scoped_lock

Defined in header <mutex>

?

?

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)

二次

代码语言:javascript
复制
#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';
}

二次

可能的产出:

二次

代码语言:javascript
复制
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)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com