stdthread(8)并发recursive_mutex 递归锁
生活随笔
收集整理的這篇文章主要介紹了
stdthread(8)并发recursive_mutex 递归锁
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 使用場景:死鎖
MutexLock mutex; void foo() { mutex.lock(); // do something mutex.unlock(); } void bar() { mutex.lock(); // do something foo(); mutex.unlock(); }1.1 解決方案
#include <iostream> #include <thread> #include <mutex>class X {std::recursive_mutex m;std::string shared;public:void fun1() {std::lock_guard<std::recursive_mutex> lk(m);shared = "fun1";std::cout << "in fun1, shared variable is now " << shared << '\n';}void fun2() {std::lock_guard<std::recursive_mutex> lk(m);shared = "fun2";std::cout << "in fun2, shared variable is now " << shared << '\n';fun1(); // ① 遞歸鎖在此處變得有用std::cout << "back in fun2, shared variable is " << shared << '\n';}; };int main() {X x;std::thread t1(&X::fun1, &x);std::thread t2(&X::fun2, &x);t1.join();t2.join(); }總結
以上是生活随笔為你收集整理的stdthread(8)并发recursive_mutex 递归锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: stdthread(7)并发unique
- 下一篇: stdthread(9)死锁deadlo