// 1111111.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex> int gcounter = 0;
std::mutex gmtx;
std::mutex gmtxOutput; void Increases() {
for (int i = 0; i<10000; ++i) {
if (gmtx.try_lock()) { // only increase if currently not locked:
++gcounter;
gmtx.unlock();
}
else{
gmtxOutput.lock();
std::cout << "try lock failed" << std::endl;
gmtxOutput.unlock();
}
}
} int _tmain(int argc, _TCHAR* argv[]) {
std::thread threads[10];
for (int i = 0; i<10; ++i)
threads[i] = std::thread(Increases); for (auto& th : threads)
th.join();
std::cout << "counter is " << gcounter << std::endl; return 0;
}

输出:

try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
try lock failed
counter is 99983
请按任意键继续. . .

这个例子说明了 try_lock() 与 lock()的区别

try_lock()会对能否上锁进行测试 并返回布尔值

而lock()则直接进行锁定 不能锁定则阻塞直到锁定

最新文章

  1. C# - 缓存OutputCache(二)缓存详细介绍
  2. 3-PHP全部编码UTF-8
  3. C# 科学计数法转换成数字
  4. UDT中的epoll
  5. HTML 学习笔记 CSS(选择器4)
  6. WP8.1&amp;Win10幸运大转盘源码分享
  7. Java学习----finally块
  8. 那么 Appium 到底是怎么工作的呢?
  9. 部署maria数据库到linux(源码编译安装)
  10. 【mysql】must reset your password using ALTER USER statement before executing this statement
  11. linux配置Anaconda python集成环境
  12. ASP.NET Core OceLot 微服务实践
  13. React 入门学习笔记整理(四)—— 事件
  14. SQL Server ltrim(rtrim()) 去不掉空格
  15. ubuntu12.04下安装Apache+PHP+MySQL
  16. python3: 数字日期和时间(1)
  17. centos7下创建mysql5.6多实例
  18. 滑动窗口的最大值 &#183; sliding-window-maximum
  19. Flink--Streaming Connectors
  20. Hbase(六) hbase Java API

热门文章

  1. Mysql-表关系
  2. Ingress.yaml
  3. idea建立一个maven项目
  4. docker使用笔记1
  5. nginx 无法访问root权限的文件内容
  6. Haskell语言学习笔记(42)Bifunctor
  7. 迷你MVVM框架 avalonjs 学习教程21、双向绑定链
  8. Week4-作业1:阅读笔记与思考
  9. 实例学习SSIS(一)
  10. 项目中调试SQLServer 方便的查看SQL语句的执行时间的方法