C++多线程-chap2多线程通信和同步5
这里,只是记录自己的学习笔记。
unique_lock c++11
- unique_lock C++11 实现可移动的互斥体所有权包装器
- 支持临时释放锁 unlock
- 支持 adopt_lock (已经拥有锁,不加锁,出栈区会释放)
- 支持 defer_lock (延后拥有,不加锁,出栈区不释放)
- 支持 try_to_lock 尝试获得互斥的所有权而不阻塞,获取失败退出栈区不会释放,通过onws_lock() 函数判断
- 支持超时参数,超时不拥有锁
1 #include <iostream> 2 #include <string> 3 #include <mutex> 4 #include <thread> 5 6 using namespace std; 7 8 int main() { 9 { 10 static mutex mux; 11 { 12 unique_lock<mutex> lock(mux); 13 lock.unlock(); 14 15 //临时释放锁 16 lock.lock(); 17 } 18 19 { 20 //已经拥有锁,不锁定,退出解锁 21 mux.lock(); 22 unique_lock<mutex> lock(mux, adopt_lock); 23 } 24 25 { 26 //延后加锁,不拥有(_Owns属性为false),退出不解锁 27 unique_lock<mutex> lock(mux, defer_lock); 28 29 //加锁,退出栈区 解锁 30 lock.lock(); 31 } 32 33 { 34 35 mux.lock(); 36 //尝试加锁,不阻塞,失败不拥有锁 37 unique_lock<mutex> lock(mux, try_to_lock); 38 if (lock.owns_lock()) { 39 cout << "owns_lock" << endl; 40 } 41 else { 42 cout << "not owns_lock " << endl; 43 } 44 mux.unlock(); 45 } 46 } 47 48 getchar(); 49 return 0; 50 }
shared_lock 共享锁(读锁)
unique_lock 互斥锁(写锁)
shared_lock C++14 实现可移动的共享互斥体所有权封装器 explicit shared_lock(mutex_type& _Mtx) : _Pmtx(_STD addressof(_Mtx)), _Owns(true) { // construct with mutex and lock shared _ Mtx.lock_shared(); }
1 #include <iostream> 2 #include <string> 3 #include <thread> 4 #include <mutex> 5 #include <shared_mutex> 6 using namespace std; 7 8 int main() { 9 { 10 //共享锁 11 static shared_timed_mutex tmux; 12 //读取锁 --> 共享锁 13 { 14 //调用共享锁 15 shared_lock<shared_timed_mutex> lock(tmux); 16 //退出栈区,释放共享锁 17 cout << "read data " << endl; 18 } 19 20 //写入锁 --> 互斥锁 21 { 22 unique_lock<shared_timed_mutex> lock(tmux); 23 cout << "write data " << endl; 24 } 25 } 26 27 28 return 0; 29 }