Lock Multiple Mutexes Safely with std::scoped_lock
Avoid lock-ordering deadlocks in C++17 and C++20 by locking several mutexes at once with std::scoped_lock, with a bank transfer example and the pitfalls.

One mutex per object is a sound default. The trouble starts when an operation needs two objects at once, for example moving money between two accounts. If thread A locks account 1 and then account 2, while thread B locks account 2 and then account 1, each can hold one lock and wait forever for the other. That is a deadlock, and it is a timing bug: the program works for a month and then hangs. C++17 added std::scoped_lock, which locks any number of mutexes together using a deadlock-avoidance algorithm, so the order you write them in stops mattering. This post shows the failure, the fix, and the rules that still apply, using GCC 14 with -std=c++20.
The deadlock in code
Here is a transfer function that looks reasonable.
#include <mutex>
#include <thread>
#include <iostream>
struct Account {
std::mutex m;
long balance = 1000;
};
void transfer(Account &from, Account &to, long amount) {
std::lock_guard<std::mutex> a(from.m);
std::lock_guard<std::mutex> b(to.m);
from.balance -= amount;
to.balance += amount;
}
int main() {
Account x, y;
std::thread t1([&] { for (int i = 0; i < 100000; i++) transfer(x, y, 1); });
std::thread t2([&] { for (int i = 0; i < 100000; i++) transfer(y, x, 1); });
t1.join();
t2.join();
std::cout << x.balance << " " << y.balance << "\n";
}Thread t1 locks x then y. Thread t2 locks y then x. Whenever t1 has taken x and t2 has taken y before either takes its second lock, both wait on each other for good. On many runs the program finishes and prints 1000 1000. On others it hangs with both threads blocked in lock. A hang that appears only under load is characteristic of lock-order bugs, and it will not show up in a short test.
The classical cure is a global lock order: always lock the account with the lower address, or lower id, first. That works and you must keep it consistent everywhere. std::scoped_lock removes that burden.
std::scoped_lock
std::scoped_lock, declared in <mutex> since C++17, takes one or more mutexes in its constructor. With more than one it behaves as if it called std::lock on all of them, which the standard specifies as using a deadlock avoidance algorithm: it may try locks and back off so that no ordering of arguments can deadlock. The destructor unlocks all of them. The [cppreference page for std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock) documents this behavior.
#include <mutex>
#include <thread>
#include <iostream>
struct Account {
std::mutex m;
long balance = 1000;
};
void transfer(Account &from, Account &to, long amount) {
std::scoped_lock lk(from.m, to.m);
from.balance -= amount;
to.balance += amount;
}
int main() {
Account x, y;
std::thread t1([&] { for (int i = 0; i < 100000; i++) transfer(x, y, 1); });
std::thread t2([&] { for (int i = 0; i < 100000; i++) transfer(y, x, 1); });
t1.join();
t2.join();
std::cout << x.balance << " " << y.balance << "\n";
}1000 1000The two threads still pass their arguments in opposite orders, and std::scoped_lock still cannot deadlock them. Each thread moves 100,000 units one way and the same amount back, so both balances return to 1000. The class template argument deduction in std::scoped_lock lk(from.m, to.m); fills in std::scoped_lock<std::mutex, std::mutex>, so you do not write the template arguments.
What std::lock does underneath
std::scoped_lock is a convenience over the function std::lock(m1, m2, ...). The standard does not specify the algorithm, only that it avoids deadlock. A common implementation locks the first mutex, then calls try_lock on the others in turn. If a try_lock fails, it unlocks everything it holds and starts again with the failing mutex first. So the thread never waits while holding a lock another thread needs. libstdc++ in GCC implements it this way with a rotation of the argument list.
Before C++17 you wrote this by hand with two statements:
void transfer(Account &from, Account &to, long amount) {
std::unique_lock<std::mutex> a(from.m, std::defer_lock);
std::unique_lock<std::mutex> b(to.m, std::defer_lock);
std::lock(a, b);
from.balance -= amount;
to.balance += amount;
}std::defer_lock constructs the unique_lock without locking, and std::lock then locks both. Another form passes std::adopt_lock to lock_guard after calling std::lock(from.m, to.m). Both still work, and you will meet them in older code. std::scoped_lock replaces them for the plain case.
The self-transfer trap
There is one input that breaks this code, and it is easy to produce: transferring from an account to itself. transfer(x, x, 5) passes the same mutex twice to std::scoped_lock. Locking a non-recursive std::mutex twice from the same thread is undefined behavior, so the program may deadlock on itself. Guard against it.
void transfer(Account &from, Account &to, long amount) {
if (&from == &to)
return;
std::scoped_lock lk(from.m, to.m);
from.balance -= amount;
to.balance += amount;
}The address comparison is cheap, and it states the invariant the function depends on. Without it, the call looks harmless in a code review and hangs in production the first time a user selects the same account twice.
It also works with a single mutex
std::scoped_lock with one mutex is a drop-in replacement for std::lock_guard. The standard library documentation notes that scoped_lock is strictly superior for new code since it covers both cases, and C++17 style guides tend to prefer it. The one capability it lacks is the one lock_guard also lacks: unlocking early. For that, use std::unique_lock and call std::lock yourself.
#include <mutex>
std::mutex m;
int shared = 0;
void bump() {
std::scoped_lock lk(m); // same effect as lock_guard here
++shared;
}When the mutexes are different types
std::scoped_lock accepts mutexes of different types in one call, such as a std::mutex and a std::shared_mutex, because each template parameter is deduced separately. All of them must satisfy the Lockable requirements. A shared mutex locked through scoped_lock is locked in exclusive mode. To take a shared lock on one and an exclusive lock on another, use std::shared_lock with std::lock and defer_lock, since scoped_lock has no shared variant.
What it does not fix
std::scoped_lock solves the ordering problem for locks acquired in one statement. It cannot help when your code takes a second lock later, after some work, while holding the first. That nesting has the same hazard as the original, and no algorithm can fix it because the second lock is requested outside the call. If a function needs another lock partway through, either take all the locks at the top with one scoped_lock, or define and document a hierarchy and never violate it.
It also does not make your design good. Locking two objects together serializes more work than locking one, and if that happens on a hot path it can become the bottleneck. Some designs avoid the multi-lock case entirely, by funneling both objects through one lock, or by assigning ownership of an account to one thread and sending messages to it.
Finally, a stalled holder blocks everyone. The algorithm avoids a cycle, but if a thread holds a lock and sleeps on a network call, other threads wait for it exactly as with one mutex. Keep the critical section short.
Finding a deadlock when you already have one
If a program hangs and you suspect lock ordering, attach a debugger and list every thread's stack. In GDB, thread apply all bt shows each thread. Two threads whose top frames are inside __lll_lock_wait or pthread_mutex_lock, each called from a function that already holds a different mutex, are the signature of a cycle. Print the mutex's owner field with print *(pthread_mutex_t *)0x... and you will see the owner thread id of each lock pointing at the other thread.
Better to catch it before it ships. ThreadSanitizer, enabled with -fsanitize=thread in GCC and Clang, includes a lock-order-inversion detector, and it reports a potential deadlock when it sees mutex A locked before B in one place and B before A in another, even if the run never actually hangs. That is the right tool for this bug, because the interleaving that deadlocks is rare but the inverted order is visible on every run.


