/*
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

最新文章

  1. 【转】ACM博弈知识汇总
  2. 快速入门SaltStack
  3. 传递消息--第三方开源--EventBus的简单使用
  4. javascript函数自调用
  5. erlang和java通信
  6. bzoj2729
  7. Day1:T3 bfs T4 树形DP
  8. SDS 链表
  9. CentOS6 安装Sendmail + Dovecot + Roundcubemail
  10. vi和vim编辑器
  11. linux swap空间的swappiness=0
  12. 互联网创业公司如何防御 DDoS 攻击?采用CDN服务
  13. SuperMap空间数据处理与制图操作短视频汇总
  14. Lua --- 输入一个数字,输出阶乘
  15. Cecos国内集成系统基于rhel6.5
  16. 找不到dubbo:annotaion错误
  17. js统计输入文字的字节数(byte)
  18. webView内部跳转后 返回不行了
  19. TCP/IP 协议图--传输层中的 TCP 和 UDP
  20. 【云安全与同态加密_调研分析(6)】云计算及云安全主流体系架构与模型——By Me

热门文章

  1. 如何读取xml文件,根据xml节点属性查询并输出xml文件
  2. 公众号的TOKEN配置PHP代码
  3. 值得分享的Bootstrap Ace模板实现菜单和Tab页效果(转)
  4. 使用Sigar获取服务器信息
  5. android 获取屏幕高度和宽度 的方法
  6. session监听器HttpSessionBindingListener
  7. 简单实现Spring中BeanFactory原理
  8. node.js发http请求
  9. Java运行结果测试
  10. PCB标识说明