Reputation: 317
I'm trying to achieve simple deadlock in 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();
If I understand correctly, I enter f1 function, lock mutex1 and wait 10 ms. In the meantime, f2 lock mutex2. Now, functions will try to lock reverse mutexes, but they are already locked. Why my program is not getting hang and it's print ABAB... and finish?
Upvotes: 3
Views: 8377
Reputation: 317
Just in case someone want to make a simple deadlock example:
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();
Upvotes: 8