参考:
前两篇博客应该就够了,第三篇作为例子的补充
我目前只看了第一篇的内容...
-----------------------------------------------------------笔记---------------------------------------------------------
第一篇博客很适合快速入门,很简短,介绍了std::mutex 和 std::timed_mutex 的基本用法
测试文中的第一个例子调用 mutex.try_lock()
#include <iostream>
#include <thread>
#include <mutex>
void inc(std::mutex &mutex, int loop, int &counter) {
for (int i = 0; i < loop; i++) {
mutex.try_lock();
++counter;
mutex.unlock();
}
}
int main() {
std::thread threads[5];
std::mutex mutex;
int counter = 0;
for (std::thread &thr: threads) {
thr = std::thread(inc, std::ref(mutex), 1000, std::ref(counter));
}
for (std::thread &thr: threads) {
thr.join();
}
// 输出:5000,如果inc中调用的是try_lock,则此处可能会<5000
std::cout << counter << std::endl;
return 0;
}
//: g++ -std=c++11 main.cpp
View Code
第二个例子也很好(std::timed_mutex)
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
void run500ms(std::timed_mutex &mutex) {
auto _500ms = std::chrono::milliseconds(500);
if (mutex.try_lock_for(_500ms)) {
std::cout << "获得了锁" << std::endl;
} else {
std::cout << "未获得锁" << std::endl;
}
}
int main() {
std::timed_mutex mutex;
mutex.lock();
std::thread thread(run500ms, std::ref(mutex));
thread.join();
mutex.unlock();
return 0;
}
//输出:未获得锁
View Code
参考二:
原文链接: https://www.cnblogs.com/exciting/p/11163623.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/298542
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!