C++多线程-chap2多线程通信和同步4
这里,只是记录自己的学习笔记。
C++11 支持的RAII管理互斥资源 lock_guard
- C++11 实现严格基于作用域的互斥体所有权包装器
- adopt_lock c++11 类型为 adopt_lock_t,假设调用方已拥有互斥的所有权
- 通过{} 控制锁的临界区
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 #include <mutex> 5 6 using namespace std; 7 8 9 10 static mutex gmutex; 11 void TestLockGuard(int i) 12 { 13 gmutex.lock(); 14 { 15 //调用这个会报错。因为已经锁住了。。。需要调用lock_guard的一个重载构造函数。。 16 //lock_guard<mutex> lock(gmutex); 17 18 //已经拥有锁,不lock 19 lock_guard<mutex> lock(gmutex, adopt_lock); 20 //结束释放锁 21 } 22 23 { 24 //锁的作用域被限定在了 {} 范围内了 。出去之后就自动解锁了 25 lock_guard<mutex> lock(gmutex); 26 cout << "begin thread " << i << endl; 27 } 28 for (;;) { 29 { 30 lock_guard<mutex> lock(gmutex); 31 cout << "In " << i << endl; 32 } 33 this_thread::sleep_for(500ms); 34 } 35 } 36 37 int main() { 38 for (int i = 0; i < 3; i++) { 39 thread th(TestLockGuard, i + 1); 40 th.detach(); 41 } 42 43 44 getchar(); 45 return 0; 46 }
看看 LockGuard的方法实现
1 // CLASS TEMPLATE lock_guard 2 template<class _Mutex> 3 class lock_guard 4 { // class with destructor that unlocks a mutex 5 public: 6 using mutex_type = _Mutex; 7 8 explicit lock_guard(_Mutex& _Mtx) 9 : _MyMutex(_Mtx) 10 { // construct and lock 11 _MyMutex.lock(); 12 } 13 14 lock_guard(_Mutex& _Mtx, adopt_lock_t) 15 : _MyMutex(_Mtx) 16 { // construct but don't lock 17 } 18 19 ~lock_guard() noexcept 20 { // unlock 21 _MyMutex.unlock(); 22 } 23 24 lock_guard(const lock_guard&) = delete; 25 lock_guard& operator=(const lock_guard&) = delete; 26 private: 27 _Mutex& _MyMutex; 28 };