2

现代C++ [4]: std::lock_guard

 11 months ago
source link: https://no5-aaron-wu.github.io/2023/02/16/cpp-modern-4-LockGuard/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

旭穹の陋室

现代C++ [4]: std::lock_guard

发表于2023-02-16|更新于2023-05-05|语言
阅读量:3

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


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK