A strong answer
A deadlock occurs when two or more threads freeze permanently because each is waiting for a resource held by another in a cycle. Specifically, all four Coffman conditions must hold simultaneously: mutual exclusion (locks are exclusive), hold and wait (a thread holds one mutex while waiting to acquire a second), no preemption (the OS will not forcibly steal a mutex from its owner), and circular wait (Thread A holds m1 and waits for m2, while Thread B holds m2 and waits for m1).
In C++, you break circular wait or hold-and-wait in two ways:
- Combined acquisition with
std::scoped_lock(C++17) orstd::lock(C++11): When both mutexes are visible at the same call site,std::scoped_lock lk(a.mtx, b.mtx);acquires both mutexes using a deadlock-avoidance algorithm (such as try-and-back-off or address-ordered locking) and releases both automatically via RAII whenlkleaves scope—even if an exception is thrown. - Global lock hierarchy (lock ordering): When locks are acquired across separate function layers where
std::scoped_lockcannot see both mutexes at once, assign a strict total order—such as sorting mutexes by memory addressstd::less<std::mutex*>{}or assigning each layer a numeric hierarchy rank—and enforce that every thread acquires locks strictly in ascending order.
What the interviewer is listening for
- Names the four deadlock conditions and identifies circular wait as the one we break in practice.
- Shows
std::scoped_lock lk(m1, m2);(orstd::unique_lockwithstd::defer_lock+std::lock) and explains why naive sequentiallock_guards on(a, b)and(b, a)deadlock. - Mentions
if (&a == &b) return;before locking two objects (transfer(acc, acc)) so a thread does not deadlock with itself on a non-recursivestd::mutex.
Common mistakes
- Acquiring
m1in one function and calling a user callback or virtual function while still holdingm1, which may acquirem2in the opposite order. - Locking
a.mtxandb.mtxwithout checking&a == &bfirst. - Using
std::recursive_mutexas a band-aid for unclear ownership instead of fixing the locking design.