Skip to content
Tutorials Center
My learning

Topics

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.

C++
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

C++ scoped_lock with opposite argument order

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.

C++ Detecting a would-be deadlock with a timeout

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:

C++
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_lock whenever 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 m and calls another function that also locks m hangs. Split the code into a locking public function and a non-locking private one, or (rarely) use std::recursive_mutex.
  • Join cycles: a thread that waits with join() or future.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_variable without 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 bt in gdb); threads stuck in lock or futex_wait show the cycle. ThreadSanitizer (-fsanitize=thread) reports lock-order inversions even when the run did not hang.
  • Timeouts hide, they do not cure. try_lock_for is useful for detecting and logging, but the design should still avoid the cycle.