首页 > 编程语言 > 详细

C++多线程:lock_gard与unique_lock

时间:2020-04-02 20:50:58      阅读:87      评论:0      收藏:0      [点我收藏+]

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/
 

C++多线程:lock_gard与unique_lock

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!