C++多线程-chap2多线程通信和同步6
这里,只是记录自己的学习笔记。
scoped_lock C++17 用于多个互斥体的免死锁 RAII 封装器 类似lock explicit scoped_lock(_Mutexes&... _Mtxes) : _MyMutexes(_Mtxes...) { // construct and lock _STD lock(_Mtxes...); }
lock(mux1, mux2); mutex mux1, mux2; std::scoped_lock lock(mux1, mux2);
scoped_lock ,出了栈区会自动释放锁。因此,不必手动再调用 unlock() 解锁。
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 #include <mutex> 5 6 using namespace std; 7 8 static mutex mux1; 9 static mutex mux2; 10 11 void TestScope1() { 12 //模拟死锁,停100ms 等另一个线程锁 mux2 13 this_thread::sleep_for(100ms); 14 cout << "begin mux1 lock " << this_thread::get_id() << endl; 15 // mux1.lock(); 16 cout << "begin mux2 lock " << this_thread::get_id() << endl; 17 // mux2.lock();//死锁 18 19 //C++11 20 // lock(mux1, mux2); 21 22 //C++17 23 // 出了栈区, 会将这里等待锁释放掉..所以不必再手动掉unlock()解锁 24 scoped_lock lock(mux1, mux2);//解决死锁 25 26 27 cout << "TestScope1 " << this_thread::get_id() << endl; 28 this_thread::sleep_for(1000ms); 29 //mux1.unlock(); 30 //mux2.unlock(); 31 } 32 33 void TestScope2() { 34 cout << "Begin mux2 lock " << this_thread::get_id() << endl; 35 mux2.lock(); 36 this_thread::sleep_for(500ms); 37 cout << "Begin mux1 lock " << this_thread::get_id() << endl; 38 mux1.lock();//死锁 39 40 cout << "TestScope2 " << this_thread::get_id() << endl; 41 this_thread::sleep_for(1500ms); 42 mux1.unlock(); 43 mux2.unlock(); 44 } 45 46 int main() { 47 { 48 //演示死锁情况 49 { 50 thread th(TestScope1); 51 th.detach(); 52 } 53 { 54 thread th(TestScope2); 55 th.detach(); 56 } 57 } 58 59 60 getchar(); 61 return 0; 62 }