C++利用mutex和thread实现一个死锁

程序

#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

结果

在这里插入图片描述
然后就没有反应了。

猜你喜欢

转载自blog.csdn.net/qaaaaaaz/article/details/132173417