现代C++ [4]: std::lock_guard
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
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";
}
Recommend
-
76
There is a lot of debate on how the if-statements should be used for better code clarity and readability. Most of them boil down to an opinion that its completely subjective and aesthetic. And…
-
73
Static production dependency analysis.
-
42
It came to our attention that the developers of Search Guard, a security plugin for Elasticsearch from floragunn GmbH, directly copied source code from our proprietary security features into their product. In looking deepe...
-
14
Angular route guard allows us to grant or remove access to certain parts of the navigation. Another route guard, the CanDeactivate guard, even enable you to prevent a user from accidentally leaving a component with unsaved...
-
1
guard & defer Written by ...
-
7
Swift’s Guard Statement for Kotlin
-
6
oracle OTN Appreciation Day: Oracle Data Guard Fast-Start Failover ...
-
12
什么是Boot Guard?电脑启动中的信任链条解析中央处理器 (CPU)话题下的优秀回答者“无事可干”的黑客们早已经把目光从操作系统转移到固件上了,毕竟一旦攻破了固件的大门,那么...
-
5
If you’re responsible for setting up AWS accounts in your organisation you might be wondering how to ensure a secure and best practice multi-account s...
-
13
0x00 前言 在Windows 10 Enterprise和Server 2016引入的新功能Decvice Guard是一种白名单机制,可用来阻止未授权的代码执行。 简单的理解,只要是不包含微软数字签名的程序,均无法用来执行代码。 然而,如果能够找到带有微软签...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK