stdthread(8) concurrent recursive_mutex recursive lock

1. Usage scenario: deadlock

MutexLock mutex;  

void foo()  
{
    
      
    mutex.lock();  
    // do something  
    mutex.unlock();  
}  

void bar()  
{
    
      
    mutex.lock();  
    // do something  
    foo();  
    mutex.unlock();   
}  

1.1 Solutions

#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();
}

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/123881100