c++11多线程学习笔记之二 mutex使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // 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()则直接进行锁定 不能锁定则阻塞直到锁定
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步