我正试图在C ++中实现简单的死锁。
std::mutex m1;
std::mutex m2;
auto f1 = [&m1, &m2]() {
std::lock_guard<std::mutex> lg1(m1);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> lg2(m2);
std::cout << "A";
};
auto f2 = [&m1, &m2]() {
std::lock_guard<std::mutex> lg1(m2);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> lg2(m1);
std::cout << "B";
};
std::thread thread([&f1, &f2]() {
for (int i = 0; i < 100; ++i)
{
if (i % 2 == 0)
{
f1();
}
else
{
f2();
}
}
});
thread.join();
如果我理解正确,我输入f1功能,锁定静音x1并等待10 ms。在此期间,f2锁定mutex2。现在,函数将尝试锁定反向互斥锁,但它们已被锁定。为什么我的程序没有挂起,它打印ABAB ...并完成?
答案 0 :(得分:1)
以防有人想要制作一个简单的死锁示例:
std::mutex m1;
std::mutex m2;
auto f1 = [&m1, &m2]() {
std::lock_guard<std::mutex> lg1(m1);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> lg2(m2);
};
auto f2 = [&m1, &m2]() {
std::lock_guard<std::mutex> lg1(m2);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> lg2(m1);
};
std::thread thread1([&f1, &f2]() {
f1();
});
std::thread thread2([&f1, &f2]() {
f2();
});
thread1.join();
thread2.join();