參考:
前兩篇博客應該就夠了,第三篇作為例子的補充
我目前只看了第一篇的內容...
-----------------------------------------------------------筆記---------------------------------------------------------
第一篇博客很適合快速入門,很簡短,介紹了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; } //輸出:未獲得鎖
參考二: