std::lock_guard
2024-08-21 12:09:52
/*
std::lock_guard:更方便线程对于互斥量的上锁操作
std::lock_guard:在定义一个lock_guard时上锁,保证在析构或者异常时解锁
*/
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard
#include <stdexcept> // std::logic_error std::mutex mtx; void print_even (int x) {
if (x%==) std::cout << x << " is even\n";
else throw (std::logic_error("not even"));
} void print_thread_id (int id) {
try {
// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
std::lock_guard<std::mutex> lck (mtx);//对mtx上锁,保证在析构时解锁
print_even(id);
}
catch (std::logic_error&) {
std::cout << "[exception caught]\n";
}
} int main ()
{
std::thread threads[];
// spawn 10 threads:
for (int i=; i<; ++i)
threads[i] = std::thread(print_thread_id,i+); for (auto& th : threads) th.join();
getchar();
return ;
}
具体可看http://www.cnblogs.com/haippy/p/3237213.html
最新文章
- 【转】ACM博弈知识汇总
- 快速入门SaltStack
- 传递消息--第三方开源--EventBus的简单使用
- javascript函数自调用
- erlang和java通信
- bzoj2729
- Day1:T3 bfs T4 树形DP
- SDS 链表
- CentOS6 安装Sendmail + Dovecot + Roundcubemail
- vi和vim编辑器
- linux swap空间的swappiness=0
- 互联网创业公司如何防御 DDoS 攻击?采用CDN服务
- SuperMap空间数据处理与制图操作短视频汇总
- Lua --- 输入一个数字,输出阶乘
- Cecos国内集成系统基于rhel6.5
- 找不到dubbo:annotaion错误
- js统计输入文字的字节数(byte)
- webView内部跳转后 返回不行了
- TCP/IP 协议图--传输层中的 TCP 和 UDP
- 【云安全与同态加密_调研分析(6)】云计算及云安全主流体系架构与模型——By Me