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

std::lock_guard

Defined in header <mutex>

?

?

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)

二次

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

二次

可能的产出:

二次

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

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

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com