Deadlocks and lock ordering
What you will learn on this page
Section titled “What you will learn on this page”- What a deadlock is, and the four conditions that must all hold for one to happen.
- How to take several mutexes at once with
std::scoped_lock, and what it does that two separate locks do not. - How to write down a lock order for mutexes that are taken at different times, and check it with a lock-order graph.
- Why a lock must never be held while calling code you do not control, such as a callback.
- How ThreadSanitizer reports an inverted lock order even in runs that did not hang.
The problem
Section titled “The problem”A bank keeps accounts in memory and moves money between them:
- B1. Transfers between accounts run on many threads at once.
- B2. A transfer never makes or loses money. If the source holds too little, the transfer is refused and nothing changes.
- B3. Transfers between unrelated accounts must not wait for each other. A transfer from Ana to Ben must not wait for one from Chen to Dev.
- B4. A statement shows an account’s balance and the transfers that produced it, and the two must agree.
- B5. After each transfer, a listener is told about it, to send a notification. The listener is code the bank does not control.
- B6. The program must never stop making progress.
B3 rules out the simplest design, one mutex for the whole bank, in which every transfer would wait for every other. So each account gets its own mutex, and a transfer needs two of them.
The first version
Section titled “The first version”Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
bool transfer(Account& from, Account& to, std::int64_t cents) { // FLAWED const std::scoped_lock lock_from(from.mutex); // first the source... const std::scoped_lock lock_to(to.mutex); // ...then the target // The two lines above are where it goes wrong. Each takes one mutex, // and the thread keeps holding the first while it waits for the second // ("hold and wait"). The order is "whatever the caller passed": // transfer(first, second, ...) locks first, then second, while // transfer(second, first, ...) locks second, then first. If those two // calls run at once and each thread gets its first lock, each then // waits forever for the mutex the other holds: a deadlock. Nothing // crashes and nothing is reported; both threads simply stop here. // // Everything below is correct on its own. Moves `cents` from `from` to // `to` and returns true, or returns false and changes nothing if // `from` holds too little. Both locks are released when the function // returns, lock_to first, then lock_from. if (from.balance_cents < cents) { return false; } from.balance_cents -= cents; to.balance_cents += cents; return true;}This code is compiled by the build but never run as a test.
Each lock is correct on its own, and a single transfer works. Two transfers in opposite directions between the same two accounts, at the same time, can do this:
- Thread 1 runs
transfer(a, b, 1)and locksa. - Thread 2 runs
transfer(b, a, 1)and locksb. - Thread 1 tries to lock
b, which thread 2 holds, and waits. - Thread 2 tries to lock
a, which thread 1 holds, and waits.
Neither can continue, and neither will ever release what the other
needs. That is a deadlock. The program does not crash or report
anything: those two threads just stop, along with every thread that
later needs a or b.
When we ran the flawed program with two threads making 100,000 transfers each in opposite directions, it hung in each of three runs, and we stopped it after 10 seconds each time. Run with the two directions one after the other, which cannot deadlock, it finished.
The four conditions
Section titled “The four conditions”A deadlock needs all four of these at once. Removing any one makes it impossible:
| Condition | What it means | In the flawed transfer | How to remove it |
|---|---|---|---|
| Mutual exclusion | A lock can be held by only one thread. | That is what a mutex is for. | Not shared, or not changed: no lock needed at all. |
| Hold and wait | A thread holds one lock while it waits for another. | It holds from while it waits for to. |
Take every lock at once, or none: std::scoped_lock with all of them. |
| No preemption | A lock cannot be taken away from the thread that holds it. | A std::mutex is never taken away. |
If a lock cannot be had within a time limit, release every lock already held and start again (try_lock_for on a std::timed_mutex). This can livelock and is rarely the best fix. |
| Circular wait | A cycle of threads, each waiting for a lock the next one holds. | Thread 1 waits for thread 2, which waits for thread 1. | Take locks in one fixed order, so a cycle cannot form. |
The two practical fixes are the middle two rows: take locks together when you can, and in a fixed order when you cannot.
Step 1: list every place that holds two locks
Section titled “Step 1: list every place that holds two locks”Before writing the fixed version, list every function that holds more than one lock, which locks, and in what order. The bank has two kinds of mutex: one per account, and one for the ledger of all transfers.
| Function | Holds | Order |
|---|---|---|
transfer |
two account mutexes, then the ledger’s | both accounts together, then the ledger |
statement |
one account mutex, then the ledger’s | the account, then the ledger |
balance |
one account mutex | (one lock, nothing to order) |
transfer_count |
the ledger’s | (one lock, nothing to order) |
| the listener | nothing from the bank | (called after every lock is released) |
The table shows the whole lock-order story in one place. Every
account-and-ledger pair is taken in the same order, account first. The
two accounts are never ordered by hand: one std::scoped_lock takes
them. If one function took the ledger first and an account second,
the table would show it at once.
Text description of the diagram
A lock-order graph has one node for each mutex, or each kind of mutex,
and an arrow from X to Y when some code takes Y while holding X. In
the flawed version, transfer(a, b) draws an arrow from account a to
account b, and transfer(b, a) draws one from b back to a. The two
arrows make a cycle, and a cycle in this graph means a deadlock is
possible. In the fixed bank, treat the two account mutexes taken by
one std::scoped_lock as a single step that the standard promises
cannot deadlock; no arrow is drawn between them. Both transfer and statement take the ledger mutex
while holding account mutexes, so the only arrows point from accounts
to the ledger. Nothing is taken while the ledger mutex is held, and
the listener runs with no lock held at all. The graph has no cycle, so
no deadlock is possible.
Diagram source (Mermaid)
flowchart LR
subgraph flawed [Flawed: locks in argument order]
A1[account a] -- held while taking --> B1[account b]
B1 -- held while taking --> A1
end
subgraph fixed [Fixed: one order]
AC[two account mutexes, taken together] -- held while taking --> L[ledger mutex]
S[one account mutex, in statement] -- held while taking --> L
L -.-> N[listener: no lock held]
endFix 1: take two locks together
Section titled “Fix 1: take two locks together”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thread safety: safe. Any number of threads may call any member at the// same time.//// Locking:// - The accounts are fixed when the Bank is made, so finding one needs no// lock. Each account's balance is guarded by that account's mutex.// - ledger_ is guarded by ledger_mutex_.// Lock order, which every member follows:// 1. Account mutexes come before ledger_mutex_, never after it.// 2. Two account mutexes are taken together, by one std::scoped_lock.// 3. No lock is held while the listener runs.// The listener may be called from several threads at once, so it must be// safe for that. A balance it reads may already have changed again.class Bank {public: // Opens one account per entry of opening_cents, numbered 0, 1, 2, ... // `listener` is optional: the default, {}, is an empty std::function, // and then transfer() calls nobody. explicit Bank(const std::vector<std::int64_t>& opening_cents, TransferListener listener = {});
// Moves money between two different accounts. Returns false, and // changes nothing, if `from` holds less than `cents`. Throws // std::invalid_argument for an unknown account, the same account // twice, or an amount that is not above zero. Strong guarantee for the // transfer itself; if the listener throws, the exception propagates // after the transfer has been made and recorded. bool transfer(AccountId from, AccountId to, std::int64_t cents);
// Locks only that account's mutex. Throws std::invalid_argument for an // unknown account. [[nodiscard]] std::int64_t balance(AccountId id) const;
// The balance and the transfers that produced it, at one moment. // Locks the account, then the ledger (rule 1). Throws // std::invalid_argument for an unknown account. [[nodiscard]] Statement statement(AccountId id) const;
// How many transfers have been made. Locks only ledger_mutex_. [[nodiscard]] std::size_t transfer_count() const; [[nodiscard]] std::size_t account_count() const noexcept { return accounts_.size(); }
private: // One account and the mutex that guards its balance. struct Account { explicit Account(std::int64_t opening) : opening_cents(opening), balance_cents(opening) {}
const std::int64_t opening_cents; // never changes, so needs no lock mutable std::mutex mutex; // mutable: const members such as balance() lock it std::int64_t balance_cents; // guarded by mutex };
// Returns the account with that number, or throws // std::invalid_argument. No lock: the set of accounts never changes. // Two versions, so that const members get a const Account. Account& find(AccountId id); const Account& find(AccountId id) const;
// A std::mutex cannot be moved, so Account cannot either. A deque // builds each element in place and never moves it. std::deque<Account> accounts_; mutable std::mutex ledger_mutex_; std::vector<Transfer> ledger_; // guarded by ledger_mutex_ // Set once by the constructor and never changed, so reading it from // many threads needs no lock. const TransferListener listener_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Moves `cents` from one account to another and records it in the ledger,// as one step: no other thread sees the money gone from one account but// not yet in the other. Returns false if the source holds too little.// The idea, in order: refuse bad requests before any lock; lock both// accounts together; check; record; move; unlock; only then tell the// listener.bool Bank::transfer(AccountId from, AccountId to, std::int64_t cents) { // The checks come before any lock, so a bad request never blocks. if (from == to) { // Locking one std::mutex twice in one thread is undefined behavior. throw std::invalid_argument("cannot transfer from an account to itself"); } if (cents <= 0) { throw std::invalid_argument("amount must be above zero"); } // find() throws std::invalid_argument for an unknown account. It needs // no lock, and the references stay valid: accounts are never added, // removed, or moved after the Bank is made. Account& source = find(from); Account& target = find(to); // Built before the locks, so the listener can be given this copy after // they are released, without reading any guarded data. const Transfer done{from, to, cents}; { // the account locks' scope // Rule 2: both accounts at once. scoped_lock locks them with a // deadlock-avoidance algorithm, whatever order they are named in. const std::scoped_lock accounts(source.mutex, target.mutex); // Both balances are now this thread's alone until the closing brace below. if (source.balance_cents < cents) { return false; // too little money: unlocks both, nothing changed } { // Rule 1: the ledger after the accounts. push_back can throw, // so it comes before the balances change. const std::scoped_lock ledger(ledger_mutex_); ledger_.push_back(done); } // ledger_mutex_ released here; the account mutexes are still held // Plain arithmetic, which cannot throw, so once the ledger has the // entry the transfer always completes. source.balance_cents -= cents; target.balance_cents += cents; } // both account mutexes released here // Rule 3: every lock is released before code we do not control runs. // A std::function converts to false when it is empty (no listener). // If the listener throws, the exception leaves transfer(), but the // money has already moved and been recorded. if (listener_) { listener_(done); } return true;}How this code works: Bank::transfer: which locks are held when
Follow one call, transfer(0, 1, 4'00) (400 cents, from account 0 to
account 1), through the function and watch which mutexes this thread
holds at each point.
| Step | What happens | Locks held |
|---|---|---|
| 1 | from == to and cents <= 0 are checked; both are false |
none |
| 2 | find(0) and find(1) return references to the two accounts |
none |
| 3 | done is built: Transfer{0, 1, 400} |
none |
| 4 | std::scoped_lock accounts(...) locks both account mutexes, waiting if either is busy |
account 0, account 1 |
| 5 | the balance check: if account 0 holds less than 400, return false |
account 0, account 1 |
| 6 | the ledger lock is taken and done is appended |
account 0, account 1, ledger |
| 7 | the inner block ends | account 0, account 1 |
| 8 | 400 moves from account 0 to account 1 | account 0, account 1 |
| 9 | the outer block ends | none |
| 10 | the listener, if there is one, is called with done |
none |
| 11 | return true |
none |
Read down the last column and the three rules from the header appear:
- Rule 2: the two account mutexes arrive together, in step 4, and leave together, in step 9.
- Rule 1: the ledger mutex is only ever taken while the account mutexes are already held (step 6), never the other way round.
- Rule 3: the listener runs in step 10, with the column empty.
Every early exit leaves nothing locked. A throw in steps 1 or 2 happens
before any lock. return false in step 5, or a throw from push_back in
step 6, leaves through the closing braces, and each std::scoped_lock
unlocks its mutexes in its destructor. In all of those cases no balance
has changed and nothing was recorded.
std::scoped_lock accounts(source.mutex, target.mutex)locks both mutexes before the next line runs. It uses the same algorithm asstd::lock, which the standard says locks all its arguments by a sequence oflock,try_lock, andunlockcalls that does not result in deadlock. A common way to do that is to lock one mutex, then only try the other; if it is taken, release the first, and start again from the one that was busy. With that algorithm the thread never blocks while holding one of them, so hold and wait cannot arise for this pair. The standard does not require this algorithm, only that the calls do not deadlock (it does not rule out livelock), and that promise is all the design relies on.- The order the mutexes are named in does not matter.
transfer(a, b)andtransfer(b, a)name them in opposite orders, and still cannot deadlock each other. Themainprogram below runs exactly that. - A transfer to the same account is rejected first. Passing one
std::mutextostd::scoped_locktwice means locking it twice from one thread, which is undefined behavior. The check comes before any lock. - The ledger comes after the accounts (rule 1). It is a third mutex, taken inside the first lock, so its order matters too: see Fix 2.
- The strong guarantee.
push_backcan throw, so it runs before either balance changes. If it throws, the transfer is not recorded and no money has moved, and the locks are released by their destructors on the way out, as in Exception safety. The guarantee covers the transfer itself. The listener runs after the transfer is made and recorded, so if the listener throws, the exception leavestransferbut the money has still moved. The header says so.
Fix 2: a written order for locks taken at different times
Section titled “Fix 2: a written order for locks taken at different times”std::scoped_lock can take several locks together only if the code
needs all of them from the start. transfer does not: it takes the
ledger only after the balance check succeeds, so a refused transfer
never touches it, and that makes the ledger a nested lock. Every other
function that takes an account and the ledger, such as statement,
must then follow the same nested order, account first, rather than
mixing it with a std::scoped_lock whose algorithm the standard does
not specify. For cases like these, the fix is an
order: a rule that every function follows, so that a cycle cannot
form.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Returns one account's opening balance, current balance, and every ledger// entry into or out of it, all from the same moment. Throws// std::invalid_argument for an unknown account.Statement Bank::statement(AccountId id) const { const Account& account = find(id); // Rule 1: the account, then the ledger. While this account is locked, // no transfer into or out of it can run, so the balance and the // entries agree. const std::scoped_lock account_lock(account.mutex); const std::scoped_lock ledger_lock(ledger_mutex_); // {} starts the entries empty; the loop fills them in. Statement result{account.opening_cents, account.balance_cents, {}}; // Scans the whole ledger, every account's transfers, keeping the ones // that touch this account. Both locks are held for the whole scan. for (const Transfer& entry : ledger_) { if (entry.from == id || entry.to == id) { result.entries.push_back(entry); // a copy of the entry } } return result; // both locks are released after the result is built}- Rule 1 says accounts before the ledger.
transferandstatementboth follow it. Ifstatementlocked the ledger first and then the account, then a statement holding the ledger and waiting for accounta, and a transfer holdingaand waiting for the ledger, would deadlock. - The rule is written in the class’s header, where the next person to add a member will see it, next to the list of which mutex guards which data. A lock order that exists only in the original author’s head is a deadlock waiting for the next change.
- Holding the account lock is what makes the statement consistent
(B4). Every transfer that changes this account holds its mutex, so
while
statementholds it, the balance and the ledger entries for this account cannot change.
Ordering by id when the set of locks is known only at run time
Section titled “Ordering by id when the set of locks is known only at run time”Sometimes code must lock a set of objects that it learns only at
run time, such as every account in an audit. std::scoped_lock
needs its mutexes as separate arguments, so it cannot take a vector.
Then the order is usually by a stable id:
// Lock order for accounts locked one by one: increasing id.// Takes the accounts by value: this function sorts its own copy of the// list of pointers, not the caller's. Returns the locks, all held.std::vector<std::unique_lock<std::mutex>> lock_in_id_order(std::vector<Account*> accounts) { // Sort the pointers by account id; the lambda says which comes first. std::sort(accounts.begin(), accounts.end(), [](const Account* x, const Account* y) { return x->id() < y->id(); }); // std::unique keeps the first of each run of equal neighbours at the // front and returns the new end; what is left after it is unspecified, // and erase removes it. Sorted first, so every repeat of the same // account is a neighbour, and each account is left once. accounts.erase(std::unique(accounts.begin(), accounts.end()), accounts.end()); std::vector<std::unique_lock<std::mutex>> locks; for (Account* account : accounts) { // Builds a std::unique_lock in the vector, which locks the mutex // now and waits if another thread holds it. locks.emplace_back(account->mutex); // in increasing id order } // The vector, and every lock in it, is moved out to the caller. return locks; // unlocked when the vector is destroyed}This code is illustrative and was not compiled.
Removing duplicates matters for the same reason as the self-transfer
check: one mutex locked twice is undefined behavior. If a group of
mutexes is sometimes locked by std::scoped_lock and sometimes by id
order, think about both rules together, and prefer to choose one
rule for each group of mutexes; the example uses std::scoped_lock
for accounts because it never needs more than two.
Fix 3: never call unknown code while holding a lock
Section titled “Fix 3: never call unknown code while holding a lock”B5 says a listener hears about every transfer. transfer calls it at
the very end, after both blocks have closed. Calling it inside the
lock would look the same, and would be wrong in three ways:
- The listener may call back into the bank. A listener that shows
the new balance calls
bank.balance(to), which locks the target account’s mutex. Iftransferstill held that mutex, the thread would be waiting for itself: undefined behavior for astd::mutex, and a hang in practice. - The listener may take its own locks. Then there is a new arrow in the lock-order graph, from the account to the listener’s mutex, that nobody can see from the bank’s code. If the listener’s own code ever calls the bank while holding its mutex, the graph has a cycle.
- The listener may be slow. Sending a notification can take seconds. Every transfer touching those accounts would wait (B3).
So transfer builds the Transfer value first, does the work under
the locks, releases them, then calls the listener with that value. The
listener may be called from several transferring threads at once, so
the header also says it must be safe for that. The test checks the first case directly:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sets up a bank whose listener calls back into the same bank. Proves// that transfer() calls the listener with no lock held (otherwise the// test hangs) and that the listener sees the transfer already finished.LLD_TEST(the_listener_runs_after_the_locks_are_released) { // The listener must be written before the Bank exists, so it cannot // name `bank` yet. It captures this pointer by reference instead, and // the pointer is set to the bank just after the bank is made. const Bank* self = nullptr; std::vector<std::int64_t> seen; // what the listener saw, in order // The listener runs on the thread that calls transfer(), here the // test's own thread, so `seen` needs no lock. Bank bank({10'00, 0}, [&self, &seen](const Transfer& done) { // Calling back into the bank locks an account mutex. If transfer() // still held it, this thread would wait for itself forever. seen.push_back(self->balance(done.to)); seen.push_back(static_cast<std::int64_t>(self->transfer_count())); }); self = &bank;
LLD_CHECK(bank.transfer(0, 1, 4'00)); // 4.00 from account 0 to account 1 LLD_CHECK_EQ(seen.size(), 2u); // the listener ran exactly once LLD_CHECK_EQ(seen[0], 4'00); // the listener sees the finished transfer LLD_CHECK_EQ(seen[1], 1); // and the transfer was already in the ledger}If the listener ran under the account lock, this test would not fail; it would hang. The listener also sees the transfer already finished, which is what a notification should report. Observer met the same problem from another side: a listener that detached itself while the subject was in the middle of notifying.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { // Amounts are in cents. The ' in 100'00 only separates digits (C++14), // so 100'00 is 10000 cents, written to read as 100.00. bank::Bank bank({100'00, 100'00, 100'00}); // three accounts, 100.00 each
// Two threads move money in opposite directions between the same two // accounts at the same time: the pattern that deadlocks the flawed // version. // Each lambda captures `bank` by reference: both threads share the one // Bank, which lives in main() and outlives them. { std::jthread forward([&bank] { for (int i = 0; i < 10'000; ++i) { bank.transfer(0, 1, 1); } }); std::jthread backward([&bank] { for (int i = 0; i < 10'000; ++i) { bank.transfer(1, 0, 1); } }); } // both joined: each std::jthread waits for its thread when destroyed // Each direction moved one cent 10,000 times, so accounts 0 and 1 are // back at 10000 cents each. std::cout << "after 20000 opposite transfers: " << bank.balance(0) << ' ' << bank.balance(1) << " cents\n";
// Account 2 holds 10000 cents (100.00), less than the 15000 asked for, // so this is refused: transfer() returns false and changes nothing. const bool moved = bank.transfer(2, 0, 150'00); std::cout << "transfer of 150.00 from account 2: " << (moved ? "done" : "refused") << '\n';
// Account 2 took part in no transfer, so its statement has no entries. const bank::Statement statement = bank.statement(2); std::cout << "account 2: opened with " << statement.opening_cents << ", holds " << statement.balance_cents << ", " << statement.entries.size() << " transfers\n"; std::cout << "transfers recorded: " << bank.transfer_count() << '\n';}after 20000 opposite transfers: 10000 10000 centstransfer of 150.00 from account 2: refusedaccount 2: opened with 10000, holds 10000, 0 transferstransfers recorded: 20000- 20,000 transfers in opposite directions between accounts 0 and 1, at the same time, finish. That is the pattern that hung the flawed version every time we ran it. Each direction moves one cent 10,000 times, so both accounts end where they started.
- The transfer of 150.00 is refused (B2), because account 2 holds 100.00, and its statement shows no transfers and an unchanged balance.
Testing
Section titled “Testing”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one// if the two values are not equal, and prints both. They come from the// site's small test header, lld_test.hpp, and must run on the main thread.
// Sets up five accounts and 8 threads ("clerks") that each try 5,000// random transfers among them, in every direction at once. Proves that// money is conserved, that no balance went below zero, and that the// ledger holds exactly the transfers that succeeded. Finishing at all// shows that this run did not deadlock.LLD_TEST(money_is_neither_made_nor_lost_by_concurrent_transfers) { // 100.00 + 200.00 + 50.00 + 0 + 75.00 = 425.00 in total. const std::vector<std::int64_t> opening{100'00, 200'00, 50'00, 0, 75'00}; Bank bank(opening); std::atomic<std::size_t> done{0}; // successful transfers, from every clerk { std::vector<std::jthread> clerks; for (unsigned seed = 1; seed <= 8; ++seed) { clerks.emplace_back([&bank, &done, seed] { // A seeded generator gives the same "random" numbers on // every run, so a failure can be repeated. A std::mt19937 // is not thread safe, so each thread has its own. std::mt19937 random(seed); // each thread its own generator std::uniform_int_distribution<AccountId> account(0, 4); // 0 to 4 std::uniform_int_distribution<std::int64_t> amount(1, 40'00); // up to 40.00 for (int i = 0; i < 5000; ++i) { const AccountId from = account(random); // Adds 1 to 4 to `from`, wrapping round at 5, so `to` // is any of the other four accounts but never `from`. const AccountId to = (from + 1 + account(random) % 4) % 5; // never from // false (too little money) is an expected outcome here. if (bank.transfer(from, to, amount(random))) { done.fetch_add(1); } } }); } } // joined: if two transfers deadlocked, this would never finish // Every clerk has finished, so the balances no longer change. std::int64_t total = 0; bool negative = false; for (AccountId id = 0; id < bank.account_count(); ++id) { total += bank.balance(id); negative = negative || bank.balance(id) < 0; } LLD_CHECK_EQ(total, 425'00); LLD_CHECK(!negative); LLD_CHECK_EQ(bank.transfer_count(), done.load());}
// Sets up an auditor thread that takes statements of all three accounts,// over and over, while three clerk threads transfer. Checks that every// statement agrees with itself: its opening balance plus the money in,// minus the money out, equals its balance.LLD_TEST(every_statement_agrees_with_itself_while_transfers_run) { Bank bank({100'00, 100'00, 100'00}); // Written by the auditor, read by the main thread after the join. std::atomic<int> disagreements{0}; std::atomic<int> statements{0}; // A one-time gate: wait() blocks until count_down() brings 1 to 0. std::latch auditor_started{1}; { // The body takes a std::stop_token, so the auditor can be asked to // stop; [&] captures everything it uses by reference. std::jthread auditor([&](std::stop_token stop) { auditor_started.count_down(); // tells the main thread "running" // do ... while: at least one round of three statements, even // if the stop request comes early. do { for (AccountId id = 0; id < 3; ++id) { const Statement s = bank.statement(id); std::int64_t expected = s.opening_cents; // Money in adds, money out subtracts: ?: picks the sign. for (const Transfer& entry : s.entries) { expected += (entry.to == id ? entry.cents : -entry.cents); } if (expected != s.balance_cents) { disagreements.fetch_add(1); } statements.fetch_add(1); } } while (!stop.stop_requested()); }); auditor_started.wait(); // the clerks start only once the auditor runs std::vector<std::jthread> clerks; for (AccountId from = 0; from < 3; ++from) { clerks.emplace_back([&bank, from] { for (int i = 0; i < 3000; ++i) { // Clerk `from` sends to the next account, then the one // after (wrapping round at 3), never to itself, 1 to 5 // cents at a time. static_cast<void> says the result // (moved or refused) is ignored on purpose. static_cast<void>(bank.transfer(from, (from + 1 + i % 2) % 3, 1 + i % 5)); } }); } // The clerks were declared last, so they are joined first; then the // auditor is asked to stop and joined. } LLD_CHECK(statements.load() > 0); LLD_CHECK_EQ(disagreements.load(), 0);}- Money is conserved. Eight threads make 40,000 random transfers among five accounts. Afterwards the total is what the accounts opened with, no balance is negative, and the ledger holds as many transfers as reported success.
- Every statement agrees with itself. An auditor thread takes statements while three threads transfer, and counts any whose opening balance plus its entries is not its balance. It takes at least one round of statements, and the test checks that it took some; how many overlap the transfers depends on scheduling.
- A deadlock shows up as a hang. If two transfers deadlocked, joining the threads would never finish. Every test in the examples has a 120-second CTest timeout, so a hang becomes a failure. It is a slow and uninformative failure, but better than a test that passes.
ThreadSanitizer finds the order, not just the hang
Section titled “ThreadSanitizer finds the order, not just the hang”A deadlock needs an unlucky interleaving, and a test may never produce one. ThreadSanitizer also records, for every lock a thread takes, which locks that thread already holds, and reports when two mutexes are taken in both orders, even if the run did not deadlock. We ran the flawed program under TSan with the two directions one after the other, so it could not hang. It finished, and TSan reported this, shortened here:
WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock) Mutex M1 acquired here while holding mutex M0 in thread T1: #4 transfer(Account&, Account&, long) lock_order_deadlock.cpp:22:28 Mutex M0 acquired here while holding mutex M1 in thread T2: #4 transfer(Account&, Account&, long) lock_order_deadlock.cpp:22:28Line 22 is the second lock, lock_to. TSan then made the program exit
with status 66. So a test with the same mistake fails under the tsan
preset if the run finishes; if it hangs, TSan still prints the report,
and the timeout fails the test. The examples’ tests run under that
preset, and report nothing for the fixed bank. That is evidence that
the orders the tests took are consistent, not proof: TSan sees only
the orders that the tests actually took.
The design at a glance
Section titled “The design at a glance”class bank::Bank
safe; lock order: accounts before ledger, two accounts together, no lock during the listener
Data members
std::deque<Account> accounts_;fixed at constructionmutable std::mutex ledger_mutex_;std::vector<Transfer> ledger_;guarded by ledger_mutex_const TransferListener listener_;
Member functions
explicit Bank(const std::vector<std::int64_t>& opening_cents, TransferListener listener = {});bool transfer(AccountId from, AccountId to, std::int64_t cents);strong; false if too little moneystd::int64_t balance(AccountId id) const;Statement statement(AccountId id) const;balance and entries at one momentstd::size_t transfer_count() const;
class bank::Bank::Account
private
Member functions
const std::int64_t opening_cents;mutable std::mutex mutex;std::int64_t balance_cents;guarded by mutex
class bank::Transfer
a value
Member functions
AccountId from;AccountId to;std::int64_t cents;
When this design fits, and when it does not
Section titled “When this design fits, and when it does not”Several mutexes with a written order fit when:
- Independent operations must not wait for each other (B3), and a
measurement or a requirement says one lock is too slow. Here B3 is
met only for the balances: unrelated transfers still meet briefly at
the ledger mutex, for one
push_back, and every transfer waits while a statement scans the ledger. If that matters, keep each account’s entries under that account’s own mutex. - The objects are fixed, or their lifetime is managed so that no thread can lock an object that is being destroyed. Here the accounts are made with the bank and never removed, so finding one needs no lock.
Something simpler fits better when:
- One mutex is fast enough. It has no lock order to get wrong.
- One thread can own the data. If every transfer is a message to one thread that owns all the accounts, there are no locks on the accounts at all, and no order to keep. That is the design Quality constraints described.
- The operation spans so many objects that locking them all costs more than the work. Then the design probably needs a different boundary, not a cleverer lock order.
Common mistakes
Section titled “Common mistakes”- Locking two mutexes in argument order. Callers choose the
arguments, so callers choose the order. Use
std::scoped_lockwith both, or order them by something stable. - Two separate
std::scoped_locks where one would do. Each locks one mutex; together they are hold and wait again. Name both in onestd::scoped_lock. - Locking the same mutex twice, through a transfer to the same account or a repeated element in a list. Check first.
- An order that is not written down. The next member function breaks it without knowing.
- Calling a callback, a virtual function on someone else’s object, or a logger that takes its own lock, while holding a lock. Copy what it needs, release, then call.
- Waiting on something else while holding a lock: joining a thread, waiting for a future, or waiting for a reply. The other side may need the lock to finish.
- Using
std::recursive_mutexto stop a hang. It hides a re-entrant call that sees half-finished state.
When the requirements change
Section titled “When the requirements change”- “Each transfer pays a fee to the bank’s own account.” A transfer
now touches three accounts:
std::scoped_lock(source, target, fee). But if the source or target is the fee account, one mutex appears twice. Handle that case first, by locking only the distinct accounts. - “Audit the total of all accounts at one moment.” That needs
every account mutex at once, a set known only at run time. Lock them
in id order, as in the snippet above, and write that rule down;
every other function that holds more than one account must then
follow an order that cannot conflict with it. Then switch
transferto lock its two accounts in id order too, since the orderstd::scoped_lockuses is unspecified. Or, if the audit only needs the total, note that transfers cannot change it (B2). - “Accounts can be opened and closed while the bank runs.” The
container of accounts now changes, so it needs its own lock, and an
account must not be destroyed while a transfer holds its mutex.
Both questions need answers before any code: who owns an account
(perhaps
std::shared_ptr, as in Ownership graphs), and where the container’s lock goes in the order. - “Notify listeners in the order the transfers happened.” Calling
each listener from the thread that made the transfer does not keep
that order. Put each
Transferon a queue, under the ledger lock, and let one thread deliver them. Asynchronous work, cancellation, and shutdown covers that thread.
Exercise
Section titled “Exercise”Exercise: Fix a lock ordering
A library guards its loans and its catalog with separate mutexes:
class Library {public: void borrow(MemberId member, BookId book) { const std::scoped_lock members(members_mutex_); check_member_may_borrow(member); // reads loans_ const std::scoped_lock catalog(catalog_mutex_); take_copy(book); // changes copies_ loans_[member].push_back(book); }
Report report() const { const std::scoped_lock catalog(catalog_mutex_); Report result = count_copies(); // reads copies_ const std::scoped_lock members(members_mutex_); result.loans = count_loans(); // reads loans_ return result; }
private: mutable std::mutex members_mutex_; // guards loans_ mutable std::mutex catalog_mutex_; // guards copies_ std::map<MemberId, std::vector<BookId>> loans_; std::map<BookId, std::size_t> copies_;};This code is illustrative and was not compiled.
- Describe an interleaving of
borrowandreportthat deadlocks. - Draw the lock-order graph.
- Fix it. Then ask whether two mutexes were the right design here at all.
Show the explained answer
1. Thread 1 calls borrow and locks members_mutex_. Thread 2
calls report and locks catalog_mutex_. Thread 1 now waits for
catalog_mutex_, and thread 2 for members_mutex_. Neither can
continue.
2. Two nodes, two arrows: borrow draws members → catalog, and
report draws catalog → members. The two arrows form a cycle.
3. Give the class one order, write it down, and make report
follow it:
// Lock order: members_mutex_ before catalog_mutex_, in every member.Report report() const { const std::scoped_lock members(members_mutex_); // members first, as in borrow() const std::scoped_lock catalog(catalog_mutex_); Report result = count_copies(); result.loans = count_loans(); return result;}This fragment was not compiled on its own; a complete version was
compiled, as described next. A version of this class with both members written out was compiled
with GCC 11.4 and Clang 14 and run under ThreadSanitizer with one
thread borrowing and one reporting; TSan reported nothing. Taking both
mutexes in one std::scoped_lock(members_mutex_, catalog_mutex_) at
the top of each function would also work.
The better question is whether there should be two mutexes. Every
book is either on the shelf or on loan, so the copies and the loans
must agree: the number of copies of a book on the shelf plus the
number on loan is always the number the library owns. That is one
invariant across both maps, and Thread safety
said one invariant needs one mutex. Here borrow changes both, and
report reads both, so they are always locked together anyway. One
mutex for the whole Library is simpler and has no lock order to get
wrong, and
because every operation here needs both maps, it makes no operation
wait that does not already wait. Two mutexes make sense only when some common operations use
one map without the other.
Summary
Section titled “Summary”- A deadlock needs mutual exclusion, hold and wait, no preemption, and circular wait, all at once. Remove one and it cannot happen.
- Take locks that are needed together together, with one
std::scoped_lock. The order its arguments are named in does not matter. - For locks taken at different times, write down one order in the class’s header, and check every function that holds two locks against it. A lock-order graph with no cycle cannot deadlock.
- Never lock one
std::mutextwice from one thread. Check for the same object first. - Never call unknown code under a lock. Copy what it needs, release, then call.
- A deadlock in a test shows up as a hang. Run the tests under ThreadSanitizer, which reports an inverted lock order even when the run did not hang.
- One mutex has no lock order to get wrong. Use more only when a requirement needs it.