C++

Fix C++ Deadlock with std::scoped_lock — Two Mutexes, Opposite Order, One Hang

Two threads, two mutexes, two opposite orders, and the program never finishes. This guide builds that hang on purpose, reads the output it prints before it stops, and then removes the deadlock two ways: one std::scoped_lock call that takes both mutexes at once, and one fixed locking order that every thread follows.

Written November 20, 2026 · Tested with GCC 13.3.0 · 9 min read

By the end of this guide
  • The first error: two threads, opposite order
  • Why neither function is wrong on its own
  • Fix 1: one std::scopedlock call for both mutexes
  • Fix 2: one locking order everywhere

Written November 20, 2026

Tested with GCC 13.3.0

What this guide is

A deadlock is a hang with a specific shape. Two threads each hold one mutex, and each thread then tries to lock the mutex the other thread holds. A thread that owns a mutex keeps it until it unlocks, and a call to lock a mutex that another thread owns blocks until that mutex is free. So thread A waits for thread B, thread B waits for thread A, and no code in either thread can run again. The process does not crash and does not print an error. It sits there, holding both mutexes, until something outside the program ends it.

The fix has to break the circle. One way is to never hold one mutex while waiting for another in an order another thread can reverse. std::scoped_lock, added in C++17, locks two or more mutexes in a single call using a deadlock avoidance algorithm, so two threads can ask for the same pair in opposite argument order and still not deadlock. The other way is a rule about order: every thread in the program locks the mutexes in the same order, so the reversed wait cannot form. This guide shows the hang first, then both fixes, on the same pair of transfers.

Build every program in this guide with g++ -std=c++17 -pthread -g. The -std=c++17 is required for std::scoped_lock. The -pthread links the thread support the examples need. The -g adds file and line information, which matters when a debugger or a stack print is the next step after a hang.

The first error: two threads, opposite order

The smallest reliable reproducer is two balances, two mutexes, and two transfer functions that lock the mutexes in opposite order. A short sleep after the first lock makes the hang happen every run instead of only sometimes: each thread takes its first mutex, pauses for 100 milliseconds, and only then reaches for the second one. By the time either thread reaches for its second mutex, the other thread already holds it.

C++
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>

std::mutex m1;
std::mutex m2;
int balance1 = 100;
int balance2 = 100;

void transfer_a() {
    std::lock_guard<std::mutex> lock1(m1);
    std::cout << "thread A locked m1" << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::cout << "thread A waiting for m2" << std::endl;
    std::lock_guard<std::mutex> lock2(m2);
    balance1 -= 10;
    balance2 += 10;
    std::cout << "thread A transferred 10" << std::endl;
}

void transfer_b() {
    std::lock_guard<std::mutex> lock1(m2);
    std::cout << "thread B locked m2" << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::cout << "thread B waiting for m1" << std::endl;
    std::lock_guard<std::mutex> lock2(m1);
    balance2 -= 10;
    balance1 += 10;
    std::cout << "thread B transferred 10" << std::endl;
}

int main() {
    std::thread t1(transfer_a);
    std::thread t2(transfer_b);
    t1.join();
    t2.join();
    std::cout << "balance1 = " << balance1 << std::endl;
    std::cout << "balance2 = " << balance2 << std::endl;
    std::cout << "done" << std::endl;
    return 0;
}

Run it under timeout, because without a limit it does not end:

Terminal
$ g++ -std=c++17 -pthread -g deadlock.cpp -o deadlock
$ timeout 2 ./deadlock
thread A locked m1
thread B locked m2
thread A waiting for m2
thread B waiting for m1

That is one run's whole output: four messages and then nothing — no transfer line from either thread, no balance lines, and no done. The timeout command ended the process after 2 seconds, and the exit status of the run is 124, the status timeout reports when it has to kill the command it ran. The hang and the exit status repeat every run, but the four messages come with no order or line guarantee: the two threads write to the same stream while holding different mutexes, so nothing serializes the stream — the two waiting messages can swap order, and two messages can run together on one physical line, with the line break landing after both. What never changes is the set of messages, the absence of any transfer, balance, or done line, and status 124.

Read the four messages in this run as a timeline. Thread A locked m1 at line 12 and printed its locked message. Thread B locked m2 at line 23 and printed its locked message. Both threads then slept, woke, and printed a waiting message: thread A at line 15, just before it tries to lock m2 at line 16, and thread B at line 26, just before it tries to lock m1 at line 27. In another run the two waiting messages can appear in the opposite order; the two lock calls they precede are where both threads stop either way. Thread A holds m1 and waits for m2. Thread B holds m2 and waits for m1. Neither lock call can return, because the mutex each one wants is owned by a thread that is itself blocked.

The sleep is a teaching device, not part of the bug. Without it, the same program can finish by luck: if thread A runs both lock calls before thread B starts, there is no circle, and the transfers complete. The bug is present in that lucky run too; the timing just did not expose it. That is what makes this class of bug hard in real code. A program can pass a test suite for weeks and then hang in production the first time the two threads reach the two lock calls together. The sleep forces the overlap so the hang can be studied on demand.

Why neither function is wrong on its own

Each transfer function reads as correct code in isolation. transfer_a locks the mutex that guards the first balance, then locks the mutex that guards the second balance, then changes both balances while holding both locks. transfer_b does the same work in the other direction. The data is protected at every step: no balance changes while its mutex is free. The defect is not inside either function. It is in the pair of orders. One function locks m1 before m2, the other locks m2 before m1, and deadlock needs exactly that disagreement plus overlap in time.

This is why a fix inside only one function, chosen at random, is a coin toss, and why reading one stack at a time during a hang misleads. Attached to a hung process, a debugger shows two threads, each stopped at a lock call, each looking like the victim of the other. Both readings are true and neither is the fix. The fix is a property of the whole program: either every multi-mutex lock uses a call that cannot deadlock, or every thread acquires the mutexes in one agreed order. State the rule once, apply it at every site that takes more than one of these mutexes, and the circle cannot form again at a new site either.

A second point follows from the reproducer. The two balances must change together: a transfer that subtracts from one and adds to the other is only correct if no other thread sees the state between the two changes. That is why the program holds two mutexes at all, instead of locking one mutex per balance change. Any fix has to preserve that property. Locking and releasing m1, then locking and releasing m2, would remove the hang and break the transfer, because another thread could read both balances in the gap and see money missing. Both fixes below keep both mutexes held across both changes.

Fix 1: one std::scoped_lock call for both mutexes

The std::scoped_lock fix replaces the two separate lock steps with one object that locks both mutexes at once. Both transfer functions construct a std::scoped_lock naming both mutexes, change both balances, and let the destructor release both mutexes at the end of the function:

C++
#include <iostream>
#include <mutex>
#include <thread>

std::mutex m1;
std::mutex m2;
int balance1 = 100;
int balance2 = 100;

void transfer_a() {
    std::scoped_lock lock(m1, m2);
    balance1 -= 10;
    balance2 += 10;
    std::cout << "thread A transferred 10" << std::endl;
}

void transfer_b() {
    std::scoped_lock lock(m2, m1);
    balance2 -= 10;
    balance1 += 10;
    std::cout << "thread B transferred 10" << std::endl;
}

int main() {
    std::thread t1(transfer_a);
    std::thread t2(transfer_b);
    t1.join();
    t2.join();
    std::cout << "balance1 = " << balance1 << std::endl;
    std::cout << "balance2 = " << balance2 << std::endl;
    std::cout << "done" << std::endl;
    return 0;
}
Terminal
$ g++ -std=c++17 -pthread -g fixed_scoped.cpp -o fixed_scoped
$ ./fixed_scoped
thread B transferred 10
thread A transferred 10
balance1 = 100
balance2 = 100
done

The program runs to completion and exits with status 0. Both transfers ran, each moving 10 in opposite directions, so both balances end at 100, and the program prints done. The run repeated three times ended with status 0 and the same final lines every time. The order of the two transfer lines is the one part that changes between runs: thread B printed first in two of the three runs and thread A printed first in the third. Either thread can win the race to lock the pair first. What cannot happen is a partial win, where one thread holds one mutex and waits for the other.

Note the argument order in the two calls, because it carries the point of this fix. transfer_a passes m1, m2 at line 11. transfer_b passes m2, m1 at line 18, the same reversed order that deadlocked in the first program. With std::scoped_lock that reversal is safe. When several mutexes are given, std::scoped_lock uses a deadlock avoidance algorithm, the same algorithm as std::lock, instead of locking the mutexes one by one in argument order. The steps of that algorithm are unspecified — a series of lock, try_lock, and unlock calls — and the guarantee is the outcome rather than the steps: the call returns only with all of the mutexes owned, and it cannot deadlock against another call locking the same set. One thread ends up owning both mutexes, does its transfer, and releases both; then the other thread owns both and does its transfer.

std::scoped_lock is a scope-bound owner, like std::lock_guard. It takes ownership of the mutexes when it is constructed and releases them when it is destructed, at the end of the scope. It is not copyable. Give the object a name and a scope that covers the whole section that touches the shared data. An unnamed temporary, such as a bare std::scoped_lock(m1, m2); statement, is destroyed at the end of that statement and protects nothing after it. The same warning applies to std::lock_guard: the named object is the lock, and the name is what keeps it alive until the closing brace.

Two limits are worth stating. First, std::scoped_lock only protects against this deadlock when every thread that locks the same set uses it, or an equivalent all-at-once call. If one function still locks m1 by itself and then reaches for m2 while another thread does the reverse, the circle can form through the function that did not change. Second, std::scoped_lock needs C++17 or later. A program built as C++11 or C++14 uses the std::lock form in the notes below instead, which has existed since C++11 and uses the same deadlock avoidance algorithm.

Fix 2: one locking order everywhere

The second fix keeps the two std::lock_guard steps and removes the disagreement. Both transfer functions lock m1 first and m2 second, even though transfer_b moves money in the opposite direction:

C++
#include <iostream>
#include <mutex>
#include <thread>

std::mutex m1;
std::mutex m2;
int balance1 = 100;
int balance2 = 100;

void transfer_a() {
    std::lock_guard<std::mutex> lock1(m1);
    std::lock_guard<std::mutex> lock2(m2);
    balance1 -= 10;
    balance2 += 10;
    std::cout << "thread A transferred 10" << std::endl;
}

void transfer_b() {
    std::lock_guard<std::mutex> lock1(m1);
    std::lock_guard<std::mutex> lock2(m2);
    balance2 -= 10;
    balance1 += 10;
    std::cout << "thread B transferred 10" << std::endl;
}

int main() {
    std::thread t1(transfer_a);
    std::thread t2(transfer_b);
    t1.join();
    t2.join();
    std::cout << "balance1 = " << balance1 << std::endl;
    std::cout << "balance2 = " << balance2 << std::endl;
    std::cout << "done" << std::endl;
    return 0;
}
Terminal
$ g++ -std=c++17 -pthread -g fixed_ordered.cpp -o fixed_ordered
$ ./fixed_ordered
thread A transferred 10
thread B transferred 10
balance1 = 100
balance2 = 100
done

This program also runs to completion and exits with status 0, with both balances at 100 and done printed. The run repeated three times ended with status 0 every time, with thread A printing first in all three runs; as in the first fix, the order of the two transfer lines is a race outcome, not part of the result, and either order ends with the same balances. The reason the hang is gone is simpler than the first fix. Thread B now reaches for m1 first, and m1 is the mutex thread A takes first. If thread A holds m1, thread B blocks on its very first lock call, holding nothing. A thread that holds nothing cannot be waited on in a circle: thread A can take m2, finish, and release both, and then thread B proceeds. A consistent order turns the second thread into a plain waiter instead of a partner in a circle.

The cost of this fix is that the order is a convention, and conventions get broken by the next edit. Nothing in the code stops a future function from locking m2 first, and the compiler accepts that function without a warning. Teams that use this fix usually write the order down where the mutexes are declared, and some derive the order from something already in the data, such as locking the account with the lower account number first in a transfer between two accounts. Deriving the order from the data works when the two objects are of the same kind and carry a stable key. It gets awkward when the mutexes guard unrelated things with no natural order between them. That is the case std::scoped_lock fits best: no order needs inventing, because the call itself avoids the deadlock.

The older form: std::lock plus adopt_lock

Programs built before C++17, and code that already uses std::lock_guard, have a third form of the same all-at-once idea. std::lock(m1, m2) locks both mutexes using a deadlock avoidance algorithm and returns with both owned. The ownership then has to go somewhere, so each mutex is handed to a std::lock_guard constructed with std::adopt_lock, which tells the guard the mutex is already locked and the guard only has to unlock it at the end of the scope:

C++
std::lock(m1, m2);
std::lock_guard<std::mutex> lock1(m1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(m2, std::adopt_lock);

Skip the std::lock call and pass std::adopt_lock anyway, and the guards will unlock mutexes the thread never locked. Call std::lock and forget the guards, and the mutexes stay locked when the function returns. std::scoped_lock exists to remove both failure modes: it is the std::lock call and the two guards as one object, in one line, with nothing to pair up by hand. Prefer it in new C++17 code, and treat the std::lock form as the correct spelling for older standards and for code that passes std::unique_lock objects to std::lock instead of raw mutexes.

Recognizing a deadlock in a real program

A deadlocked program and a slow program look alike from outside for the first few seconds: no output, no progress, no error. Three signs separate them. First, the output stops at a stable point. The reproducer printed its locked and waiting messages and then nothing more, however long it was left; a slow program keeps producing output, just slowly. Second, the process uses almost no processor time while it hangs, because both threads are blocked in lock calls rather than running. Third, the hang repeats at the same place once the timing lines up, while a load problem moves around. In a debugger, the confirming picture is two or more threads each stopped inside a lock call, where the mutex each one wants is owned by another thread in the same set. Draw the arrows from each thread to the mutex it waits for, and from each mutex to the thread that owns it. A deadlock is a closed loop in that drawing.

When the drawing has no loop, the hang is something else: a thread waiting on a condition that never gets signaled, a join on a thread that is itself waiting for input, or a lock taken twice by the same thread. That last one is worth separating out, because it involves a single thread and a single mutex. std::mutex is non-recursive, and a thread must not own it before calling lock: locking it a second time from the same thread is undefined behavior, and in practice the thread typically ends up waiting on itself. The fix there is different: restructure so the inner call does not retake the lock, or use std::recursive_mutex when the design truly needs the same thread to re-enter. The two fixes in this guide do not cure a self-lock, and std::scoped_lock on a set that names the same mutex twice is not the answer to one.

The fixes, ranked

  • First, replace paired lock steps with one std::scoped_lock naming every mutex the section needs, at every site that locks that set. The call cannot deadlock against another call of the same kind, in either argument order.
  • Second, where std::scoped_lock is not available or not used, fix one acquisition order for the mutexes and follow it at every site. Derive the order from a stable key in the data when the objects have one.
  • Third, on a pre-C++17 build, use std::lock to take the set at once and hand each mutex to a guard with std::adopt_lock.
  • Fourth, audit the rest of the program for the same set of mutexes locked anywhere else. A fix that covers two sites out of three leaves the hang in place, at the third site.
  • Fifth, reproduce the hang with forced timing before and after the fix. A fix tested only on runs that never overlapped proves nothing about the overlap case.

Which fix for which cause

Cause Shape of the hang Fix
Two threads, opposite order Each holds one mutex, waits for the other std::scoped_lock on both
Same pair locked at many sites Hang moves between sites std::scoped_lock at every site
No natural order between mutexes Order rule hard to state std::scoped_lock
Same kind of object, stable key Transfers between pairs Lock lower key first, or scoped_lock
Pre-C++17 build Same opposite-order hang std::lock plus adopt_lock guards
One thread locks one mutex twice Single thread stopped at its own lock Restructure, or recursive_mutex

Checklist

  • Count the mutexes each section holds at once. Any section that holds two or more is a deadlock candidate.
  • Write down the order each section acquires them in. Two different orders for the same set is the bug, before any hang is seen.
  • Use one std::scoped_lock for the set, or one written order followed everywhere. Do not mix the two approaches across sites without checking the mixed case.
  • Name the lock object and keep its scope over the whole section that touches the shared data.
  • Keep both mutexes held across changes that must appear together. Splitting the section removes the hang and breaks the data instead.
  • Reproduce with forced overlap, then run the fixed program under the same forced timing.
  • Check for the separate self-lock case: one thread, one non-recursive mutex, taken twice.

Sources

  • cppreference, std::scoped_lock — for std::scoped_lock being a mutex wrapper that owns zero or more mutexes for the duration of a scoped block since C++17, for it using a deadlock avoidance algorithm as if by std::lock when several mutexes are given, for releasing the mutexes on destruction, for the class being non-copyable, and for the warning that an unnamed std::scoped_lock object does not hold a lock for the rest of the scope.
  • cppreference, std::lock — for std::lock locking the given objects using a deadlock avoidance algorithm since C++11, for it locking by an unspecified series of calls to lock, try_lock, and unlock, for unlocking the already locked objects if a call throws, and for std::scoped_lock being the generally preferred wrapper for the function.
  • cppreference, std::mutex — for std::mutex protecting shared data from simultaneous access by multiple threads, for its exclusive, non-recursive ownership from a successful lock or try_lock call until unlock, for other threads blocking in lock while a mutex is owned, for a thread not owning the mutex before calling lock, and for std::mutex usually being managed through std::lock_guard or std::scoped_lock in a more exception-safe manner.
  • cppreference, std::lock_guard — for std::lock_guard owning a mutex for the duration of a scoped block, for taking ownership on construction and releasing the mutex on destruction, for the class being non-copyable, and for std::scoped_lock being the alternative that locks multiple mutexes using a deadlock avoidance algorithm.

Keep Exploring