C++ uses mutex and thread to implement a deadlock

program

#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;

}

compile

g++ .\deadlock.cpp -o deadlock -lpthread

result

Insert image description here
Then there was no response.

Guess you like

Origin blog.csdn.net/qaaaaaaz/article/details/132173417