什么是死锁
当多个线程以不同的顺序锁定相同的多个互斥锁时,可能会导致死锁。这是因为一个线程可能会持有一个互斥锁,并等待另一个线程持有的锁,而第二个线程则持有第二个锁并等待第一个线程持有的锁,从而导致循环等待。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m1;
std::mutex m2;
void thread1() {
std::lock_guard<std::mutex> lck1(m1);
std::this_thread::sleep_for(std::chrono::milliseconds(10)); // 模拟一些工作
std::lock_guard<std::mutex> lck2(m2);
std::cout << "Thread 1 completed" << std::endl;
}
void thread2() {
std::lock_guard<std::mutex> lck2(m2);
std::this_thread::sleep_for(std::chrono::milliseconds(10)); // 模拟一些工作
std::lock_guard<std::mutex> lck1(m1);
std::cout << "Thread 2 completed" << std::endl;
}
int main() {
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
return 0;
}
在这个示例中,thread1
先锁定 m1
再锁定 m2
,而 thread2
则先锁定 m2
再锁定 m1
。如果 thread1
持有 m1
并等待 m2
,而 thread2
同时持有 m2
并等待 m1
,这将导致死锁。
可以看出程序在编译成功之后没有任何反应,而是“暂停”了。
解决方法 1:使用 std::lock
C++11 提供了 std::lock
函数,该函数可以一次性锁定多个互斥锁,并确保不会发生死锁。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m1;
std::mutex m2;
void thread1() {
std::lock(m1, m2); // 同时锁定 m1 和 m2
std::lock_guard<std::mutex> lck1(m1, std::adopt_lock); // 告诉 lock_guard 互斥锁已经被锁定
std::lock_guard<std::mutex> lck2(m2, std::adopt_lock);
std::cout << "Thread 1 completed" << std::endl;
}
void thread2() {
std::lock(m1, m2); // 保持锁定顺序一致
std::lock_guard<std::mutex> lck1(m1, std::adopt_lock);
std::lock_guard<std::mutex> lck2(m2, std::adopt_lock);
std::cout << "Thread 2 completed" << std::endl;
}
int main() {
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
return 0;
}
解决方法 2:使用 std::scoped_lock
(C++17)
C++17 引入了 std::scoped_lock
,它更简洁地解决了多互斥锁的并发问题,并且自动处理锁定和解锁。std::scoped_lock
可以同时锁定多个互斥锁,确保不会发生死锁。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m1;
std::mutex m2;
void thread1() {
std::scoped_lock lck(m1, m2); // 同时锁定 m1 和 m2
std::cout << "Thread 1 completed" << std::endl;
}
void thread2() {
std::scoped_lock lck(m1, m2); // 锁定顺序无关紧要
std::cout << "Thread 2 completed" << std::endl;
}
int main() {
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
return 0;
}
另外一种情况的死锁
在持有锁的时候,调用未知代码。如果不了解代码做了什么,就有死锁的风险。
void do_this(Foo* p)
{
lock_guard<mutex> lck {my_mutex};
// ... 做一 些 事 ...
p->act(my_data);
// ...
}
如果不知道 Foo::act 会干什么(可能它是一个虚函数,调用某个还未编写的某个派生类成员),
它可能会(递归地)调用 do_this 因而在 my_mutex 上造成死锁。 可能它会在某个别的 mutex
上锁定而无法在适当的时间内返回,对任何调用了 do_this 的代码造成延迟。
在lock_guard中用 recursive_mutex!