C++中的死锁问题

死锁发生在多线程编程中,一般发生在两个或者两个以上的线程相互等待对方释放资源,相互阻塞导致程序无法继续执行的现象。

一下是一个简单的例子解释了死锁现象:

#include<thread>
#include<mutex>

std::mutex mtx1,mtx2;

void thread1(){
    mtx1.lock();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    mtx2.lock();
    //Do some work...
    mtx2.unlock();
    mtx1.unlock();
}

void thread2(){
    mtx2.lock();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    mtx1.lock();
    //Do some work...
    mtx1.unlock();
    mtx2.unlock();
}

int main(){
    std::thread t1(thread1);
    std::thread t2(thread2);

    t1.join();
    t2.join();

    return 0;
}

上述代码中,线程1先锁定mtx1,然后暂停1秒,在线程1暂停的这1秒时间内,由于线程1与线程2是并发执行的,因此,线程2有机会开始执行并锁定mtx2,然后线程2在锁定mtx2后,暂停1秒,然后在这1秒内,线程1开始试图锁定mtx2,此时,mtx2已经被线程2锁定中,而线程2试图锁定mtx1,而此时,mtx1已经被线程1锁定中,这样线程1与线程2都在等待对方释放锁,就形成了死锁。

正确的写法应该是:

#include<hread>
#include<mutex>

std::mutex mtx1,mtx2;

void thread1(){
    mtx1.lock();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    mtx2.lock();
    //Do some work...
    mtx2.unlock();
    mtx1.unock();
}

void thread2(){
    mtx1.lock();
    std::this_thread::sleep_for(std::chrono::seconds(s));
    mtx2.lock();
    //Do some work...
    mtx2.unlock();
    mtx1.unlock();
}

上面代码,线程2与线程1以相同的顺序获取锁,这样两个线程就不会互相等待对方释放锁,从而避免了死锁问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值