c++11 std::mutex
参考:
前两篇博客应该就够了,第三篇作为例子的补充
我目前只看了第一篇的内容...
-----------------------------------------------------------笔记---------------------------------------------------------
第一篇博客很适合快速入门,很简短,介绍了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
第二个例子也很好(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;
}
//输出:未获得锁
参考二: