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/
 

原文链接: https://www.cnblogs.com/goingnow/p/12622404.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++多线程<mutex>:std::lock_guard

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/339448

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午12:05
下一篇 2023年3月2日 上午12:05

相关推荐