C++多線程 :std::lock_guard


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只有構造函數和析構函數,沒有其他的成員函數,所以僅僅是上鎖和解鎖的功能

參考文檔:
http://www.cplusplus.com/reference/mutex/lock_guard/
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM