例子:用mutex a锁门,用metex b去开门,结果没打开,就导致了程序的死锁。
注意:这个程序专门为了测试,mutex的问题。
#include <list>
#include <iostream>
#include <mutex>
#include <algorithm>
#include <thread>
#include <unistd.h>
using namespace std;
class data_protect{
public:
list<int> alist{1,2};
mutex m;
mutex m1;
public:
void add_list(int val){
m.lock(); //----------------①
alist.push_back(val);
}
bool contains(int val){
m1.unlock();//----------------------②
return find(alist.begin(), alist.end(), val) != alist.end();
}
};
void func(data_protect& dp){
dp.add_list(12);
}
int main(){
data_protect dp;
thread t(func, ref(dp));
//t.join();
t.detach();//---------------③
//sleep(1);
dp.add_list(12);//----------------④
if(dp.contains(12)){//------------------⑤
cout << "contains 12" << endl;
}
for(auto& s : dp.alist){
cout << s << endl;
}
pthread_exit(NULL);
}
执行结果:死锁,程序永远在等待锁的打开。
从③处开始就开了一个新的线程a,线程a调用了add_list()方法,add_list方法里,在①处是用m去上的锁。main函数线程在④处也调用了,add_list()方法,进去后,发现是上锁的状态,所以就阻塞在哪里,等着锁打开后,main函数线程好进去,然后在⑤处调用了contains方法,contains方法试图在②处用m1去解m的锁,所以就解不开①处的锁,所以就导致了一个线程一直等在①处的锁的地方,就导致了死锁。
如果把②处的m1.unlock();换成m.unlock();就能解开锁了,就不会导致死锁。
#include <list>
#include <iostream>
#include <mutex>
#include <algorithm>
#include <thread>
#include <unistd.h>
using namespace std;
class data_protect{
public:
list<int> alist{1,2};
mutex m;
public:
void add_list(int val){
lock_guard<mutex> g(m);
alist.push_back(val);
}
bool contains(int val){
lock_guard<mutex> g(m);
return find(alist.begin(), alist.end(), val) != alist.end();
}
};
void func(data_protect& dp){
dp.add_list(12);
}
int main(){
data_protect dp;
thread t(func, ref(dp));
//t.join();
t.detach();
//sleep(1);
dp.add_list(12);
if(dp.contains(12)){
cout << "contains 12" << endl;
}
for(auto& s : dp.alist){
cout << s << endl;
}
pthread_exit(NULL);
}
原文:https://www.cnblogs.com/xiaoshiwang/p/9880228.html