MiddleDebuggingCommonNot answered yet
Why can this lock ordering deadlock, and how to fix it?
Two threads run t1 and t2 concurrently and the program occasionally hangs.
std::mutex m1, m2;
void t1() { std::lock_guard<std::mutex> a(m1); std::lock_guard<std::mutex> b(m2); }
void t2() { std::lock_guard<std::mutex> a(m2); std::lock_guard<std::mutex> b(m1); }
Find and fix the bug.
Deadlock from lock-ordering inversion: t1 locks m1 then m2; t2 locks m2 then m1. If each takes its first lock at once, neither can take the second. Fix: lock in one consistent global order, or use std::scoped_lock lk(m1, m2) (C++17), which locks both atomically.
- ✗Believing short critical sections cannot deadlock
- ✗Confusing this with double-locking a non-recursive mutex
- ✗Thinking lock_guard defers acquisition to scope exit
- →How does
std::scoped_lockavoid deadlock when locking multiple mutexes? - →What is a consistent lock-ordering discipline and why does it work?