前言

std::lock_guard类是C++11新加入的特性,它是一个mutex包装器,提供了一种方便的RAII风格机制,该包装器在构造时自动绑定传入的mutex并加锁,在其析构函数中解锁,从而实现在作用域块的持续时间内拥有mutex而无需手动解锁,从而大大减少了死锁的可能性。

使用示例

#include <thread>
#include <mutex>
#include <iostream>

int g_i = 0;
std::mutex g_i_mutex; // protects g_i

void safe_increment()
{
const std::lock_guard<std::mutex> lock(g_i_mutex);
++g_i;

std::cout << "g_i: " << g_i << "; in thread #"
<< std::this_thread::get_id() << '\n';

// g_i_mutex is automatically released when lock
// goes out of scope
}

int main()
{
std::cout << "g_i: " << g_i << "; in main()\n";

std::thread t1(safe_increment);
std::thread t2(safe_increment);

t1.join();
t2.join();

std::cout << "g_i: " << g_i << "; in main()\n";
}

参考文献

[1] https://en.cppreference.com/w/cpp/thread/lock_guard