死锁发生在多线程编程中,一般发生在两个或者两个以上的线程相互等待对方释放资源,相互阻塞导致程序无法继续执行的现象。
一下是一个简单的例子解释了死锁现象:
#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以相同的顺序获取锁,这样两个线程就不会互相等待对方释放锁,从而避免了死锁问题。