Recursive lock recursive_mutex based on multithreaded concurrency-STL

One: Description

1. The recursive_mutex class is a synchronization primitive that can be used to protect shared data from simultaneous access by multiple threads.
2. recursive_mutex provides exclusive recursive ownership semantics:
3. One of the usage scenarios of recursive_mutex is to protect the shared state in the class, and the member functions of the class may call each other

Two: Usage:

The use of recursive_mutex is similar to that of mutex. It is used to restrict multiple threads from accessing the same variable at the same time. It is used to lock and ensure that multiple threads can only have one thread modifying variables at the same time; when it is different from mutex, recursive_mutex can allow the same The thread recursively locks, and the thread will release the control of the variable only when the number of locks and release times are the same; for example, fun1 is called in the following fun2, but both fun1 and fun2 are locked. If mutex is used, in Locking fun1 and locking again in fun2 will cause deadlock; so recursive_mutex can avoid the deadlock problem caused by recursive nested calls; recursive calls will not deadlock, and the same thread uses recursive_mutex to lock and unlock times Release control when equal;

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

insert image description here
If there are any mistakes or deficiencies, welcome to comment and point out! Creation is not easy, please indicate the source for reprinting. If it is helpful, remember to like and follow (⊙o⊙)
For more content, please follow my personal blog: https://blog.csdn.net/qq_43148810

Guess you like

Origin blog.csdn.net/qq_43148810/article/details/130645778