lock_guard:這個對象僅有構造函數和析構函數。沒有其他成員函數。
1 // lock_guard example 2 #include <iostream> // std::cout 3 #include <thread> // std::thread 4 #include <mutex> // std::mutex, std::lock_guard 5 #include <stdexcept> // std::logic_error 6 7 std::mutex mtx; 8 9 void print_even (int x) { 10 if (x%2==0) std::cout << x << " is even\n"; 11 else throw (std::logic_error("not even")); 12 } 13 14 void print_thread_id (int id) { 15 try { 16 // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception: 17 std::lock_guard<std::mutex> lck (mtx); 18 print_even(id); 19 } 20 catch (std::logic_error&) { 21 std::cout << "[exception caught]\n"; 22 } 23 } 24 25 int main () 26 { 27 std::thread threads[10]; 28 // spawn 10 threads: 29 for (int i=0; i<10; ++i) 30 threads[i] = std::thread(print_thread_id,i+1); 31 32 for (auto& th : threads) th.join(); 33 34 return 0; 35 }
//run 1
1 [exception caught] 2 4 is even 3 [exception caught] 4 [exception caught] 5 2 is even 6 6 is even 7 [exception caught] 8 8 is even 9 [exception caught] 10 10 is even
// run 2
[exception caught] 4 is even 10 is even [exception caught] [exception caught] 2 is even 6 is even [exception caught] 8 is even [exception caught]
std::lock_guard只有構造函數和析構函數,沒有其他的成員函數,所以僅僅是上鎖和解鎖的功能