template<class Mutex> class lock_guard;
lock_guard
是一個一直使互斥量鎖定的管理鎖對象;
在構建階段,互斥量被調用線程鎖定,在析構階段,鎖unlocked
lock_guard是最簡單的鎖,對具有自動持續時間的對象特別有用,該i持續時間能一直持續到上下文結束;
#include <iostream>
#include <mutex>
#include <thread>
#include <stdexcept>
using namespace std;
mutex mtx;
void PrintEven(int x) {
if (x % 2 == 0) {
cout<< x<< " is even"<<endl;
} else {
throw(logic_error("not even"));
}
}
void PrintThreadId(int x) {
try {
//using local lock_guard to lock mtx
//guarantees unlocking on destruction/exception
lock_guard<mutex> lck(mtx);
PrintEven(x);
} catch (logic_error&) {
cout<<" exception caught."<<endl;
}
}
int main(void) {
thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = thread(PrintThreadId, i + 1);
}
for (auto& t : threads) {
t.join();
}
return 0;
}