程序
#include<iostream>
#include<mutex>
#include<thread>
using namespace std;
mutex mtx1;
mutex mtx2;
void A(){
mtx1.lock();
cout<<"a:mtx1"<<endl;
this_thread::sleep_for(chrono::milliseconds(1000));
mtx2.lock();
cout<<"a:mtx2"<<endl;
mtx2.unlock();
mtx1.unlock();
}
void B(){
mtx2.lock();
cout<<"b:mtx2"<<endl;
this_thread::sleep_for(chrono::milliseconds(1000));
mtx1.lock();
cout<<"b:mtx1"<<endl;
mtx1.unlock();
mtx2.unlock();
}
int main(){
thread t1(A);
thread t2(B);
t1.join();
t2.join();
return 0;
}
编译
g++ .\deadlock.cpp -o deadlock -lpthread
结果
然后就没有反应了。