为了避免死锁,在使用互斥锁(mutex)时,应该遵循以下原则:
以下是一个使用互斥锁避免死锁的示例代码:
std::mutex mtx1, mtx2;
void thread1() {
std::unique_lock<std::mutex> lock1(mtx1);
// 临界区
std::cout << "Thread 1 acquired mtx1" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread 1 trying to acquire mtx2" << std::endl;
std::unique_lock<std::mutex> lock2(mtx2);
// 临界区
std::cout << "Thread 1 acquired mtx2" << std::endl;
lock1.unlock();
// 其他操作
}
void thread2() {
std::unique_lock<std::mutex> lock2(mtx2);
// 临界区
std::cout << "Thread 2 acquired mtx2" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread 2 trying to acquire mtx1" << std::endl;
std::unique_lock<std::mutex> lock1(mtx1);
// 临界区
std::cout << "Thread 2 acquired mtx1" << std::endl;
lock2.unlock();
// 其他操作
}
在上面的示例中,两个线程按照相同的顺序获取锁,并且在退出临界区时释放锁,从而避免了死锁的情况。