C++ Reference ยท Concurrency
Deadlock in C++ threads
Understand deadlock in C++ multithreading: how two threads wait on each other forever, and how scoped_lock, lock ordering and try_lock avoid it.
A deadlock happens when two or more threads each hold a resource and wait for a resource held by another, so none of them can ever continue. The classic form uses two mutexes: thread A locks m1 and then waits for m2, while thread B has locked m2 and waits for m1. Nothing in the language detects this; the program simply hangs (and on our runner it would run into the time limit).
Four conditions must all hold for a deadlock: mutual exclusion, hold-and-wait, no preemption (a lock cannot be taken away) and a circular wait. Every prevention technique removes one of them. The most practical tools are to lock several mutexes in one atomic step with std::scoped_lock, to always lock in a fixed global order, and to avoid holding a lock while calling code you do not control.
std::mutex a, b; // Deadlock-prone: one thread locks a then b, another locks b then a. // Safe: both threads use the same call, in any argument order. std::scoped_lock both(a, b);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
There is no deadlock API; the relevant tools are these:
std::scoped_lock<MutexTypes...> lock(m1, m2, ...); // C++17 template<class L1, class L2, class... Ln> int std::try_lock(L1&, L2&, Ln&...); template<class L1, class L2, class... Ln> void std::lock(L1&, L2&, Ln&...); bool timed_mutex::try_lock_for(const std::chrono::duration<R, P>&);
| Tool | Description |
|---|---|
std::scoped_lock |
RAII lock for one or more mutexes. With several mutexes it uses a deadlock-avoidance algorithm. |
std::lock(a, b, ...) |
Locks all the lockables without deadlock; you must unlock them yourself (or adopt them into guards with std::adopt_lock). |
std::try_lock(a, b, ...) |
Tries each lock in order. Returns -1 on success, otherwise the zero-based index of the first lock that could not be taken (the ones already taken are released). |
try_lock_for / try_lock_until |
Give up after a time limit instead of waiting forever (needs std::timed_mutex or recursive_timed_mutex). |
Errors / undefined behavior: locking a plain std::mutex twice from the same thread is undefined behavior (in practice usually a hang). Destroying a mutex that is still locked is undefined behavior too.
Usage notes
- Prefer
std::scoped_lockwhenever you need two or more mutexes at the same time. The order of the arguments does not matter; the implementation retries in a way that cannot form a cycle. - Fixed lock order: if you must lock one at a time, define a global order (for example by an account id or a "level" number) and always lock the lower one first. Document the order next to the mutexes.
- Do not call unknown code while holding a lock. A callback, a virtual function or a user-supplied lambda may lock something else and close a cycle.
- Self-deadlock: a function that locks
mand calls another function that also locksmhangs. Split the code into a locking public function and a non-locking private one, or (rarely) usestd::recursive_mutex. - Join cycles: a thread that waits with
join()orfuture.get()for a thread that waits for it is also a deadlock, with no mutex involved. A thread pool whose tasks wait for other tasks of the same pool can starve the same way. - Lost wake-ups: waiting on a
std::condition_variablewithout a predicate can wait forever if the notification came first. Always pass a predicate. - Diagnosing: attach a debugger and print every thread's stack (
thread apply all btin gdb); threads stuck inlockorfutex_waitshow the cycle. ThreadSanitizer (-fsanitize=thread) reports lock-order inversions even when the run did not hang. - Timeouts hide, they do not cure.
try_lock_foris useful for detecting and logging, but the design should still avoid the cycle.