Back to questionsWhat can happen if two threads call
JuniorTheoryCommon
What can happen if two threads call lock_both(a, b) and lock_both(b, a) at once?
#include <mutex>
std::mutex a;
std::mutex b;
void lock_both(std::mutex& first, std::mutex& second) {
std::lock_guard<std::mutex> g1(first);
std::lock_guard<std::mutex> g2(second);
}They can deadlock: each locks its first mutex and waits forever for the other
- Expecting the threads to take turns: if each holds its first mutex, neither gets its second. So no
lock_guardis ever destroyed to free one. - Expecting a deadlock on every run: it needs both threads to lock their first mutex before either locks its second. That depends on timing.
- How does
std::scoped_locklock two mutexes without this risk? - Why can such a program pass every test and still hang later?