stdthread并发recursive_mutex 递归锁
Posted thefist11
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了stdthread并发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并发recursive_mutex 递归锁的主要内容,如果未能解决你的问题,请参考以下文章
c++11的std::thread能用类的成员函数构造一个线程吗?语法怎样?