---
title: "Should you fix a TSan lock-order inversion when nothing ever deadlocked? | Proofline"
description: "Usually yes: TSan reports a cycle in the order locks were taken, which a different interleaving can turn into a hang."
url: https://proofline.sh/learn/threadsanitizer-lock-order-inversion/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Should you fix a TSan lock-order inversion when nothing ever deadlocked?

Usually yes: TSan reports a cycle in the order locks were taken, which a different interleaving can turn into a hang. Dismiss it only when one outer lock is held on every path that takes both locks.

Code review The Proofline team November 25, 2026 6 min read

## What TSan is reporting

ThreadSanitizer's deadlock detector does not wait for a hang. The sanitizer project's [deadlock detector page](https://github.com/google/sanitizers/wiki/ThreadSanitizerDeadlockDetector) describes the algorithm: "If a lock B is acquired while a lock A is being held by the same thread, a directed edge `A=>B` is added to the lock acquisition graph. A potential deadlock is reported when there is a cycle in the graph." The two edges can come from different threads at different times. They do not need to overlap.

The same page says to enable it with `TSAN_OPTIONS=detect_deadlocks=1` and lists the default as false. That table does not match the LLVM 18 runtime. In the LLVM 18.1.3 [sanitizer flags](https://github.com/llvm/llvm-project/blob/llvmorg-18.1.3/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc), `detect_deadlocks` defaults to `true`, with the description "If set, deadlock detection is enabled." The runs below do not set `detect_deadlocks`.

This constructed transfer function locks the source account and then the destination. Two transfers in opposite directions take the same two locks in opposite orders. The test runs them one after the other, joining the first thread before starting the second:

```
static void transfer(struct account *from, struct account *to, long amount) {
  pthread_mutex_lock(&from->mu);                     /* line 13 */
  if (pause_us) usleep(pause_us);
  pthread_mutex_lock(&to->mu);                       /* line 15 */
  from->balance -= amount;
  to->balance += amount;
  pthread_mutex_unlock(&to->mu);
  pthread_mutex_unlock(&from->mu);
}

static void *pay_bob(void *arg)   { (void)arg; transfer(&alice, &bob, 10); return NULL; }
static void *pay_alice(void *arg) { (void)arg; transfer(&bob, &alice, 5);  return NULL; }
```

Built with Ubuntu clang 18.1.3 as `clang -O1 -g -fsanitize=thread bank.c`, the program prints the correct balances and TSan still reports, exiting 66 (paths and build IDs trimmed):

```
WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock) (pid=5270)
  Cycle in lock order graph: M0 (0x...b78) => M1 (0x...ba8) => M0

  Mutex M1 acquired here while holding mutex M0 in thread T1:
    #0 pthread_mutex_lock <null> (bank+0x...)
    #1 transfer bank.c:15:3 (bank+0x...)
    #2 pay_bob bank.c:22:48 (bank+0x...)

    Hint: use TSAN_OPTIONS=second_deadlock_stack=1 to get more informative warning message

  Mutex M0 acquired here while holding mutex M1 in thread T2:
    #0 pthread_mutex_lock <null> (bank+0x...)
    #1 transfer bank.c:15:3 (bank+0x...)
    #2 pay_alice bank.c:23:48 (bank+0x...)

  Thread T1 (tid=5275, finished) created by main thread at:
  ...
ThreadSanitizer: reported 1 warnings
alice=95 bob=105
```

T1 had finished before T2 started, so these two threads could never have deadlocked. The report is about the code, not this run: `transfer` takes locks in caller-supplied order, so any two concurrent transfers in opposite directions can each hold one lock and wait for the other.

## Read both edges of the cycle

Each "acquired here while holding" block is one edge of the cycle. The first says T1 locked M1 (Bob's mutex) at line 15 while holding M0 (Alice's). The second says T2 locked M0 at line 15 while holding M1. Both edges come from the same line of the same function, which tells you the inversion is in the function's design, not in two unrelated subsystems.

By default the report shows only where the second lock was taken. Run with `TSAN_OPTIONS=second_deadlock_stack=1`, as the hint says, to also get "previously acquired by the same thread here" stacks for the first lock of each edge. You need those when the two locks are taken in different functions.

## Force the timing to see the hang

The test's sequential structure is why nothing hung, so the next fact to collect is whether a concurrent schedule can hang. A variant starts both threads before joining either. Built without TSan, the forced pause after the first lock (100 ms) widens the window:

```
$ clang -O1 -g bank_concurrent.c -o conc_plain
$ timeout 5 ./conc_plain 0;      echo "exit=$?"
alice=95 bob=105
exit=0
$ timeout 5 ./conc_plain 100000; echo "exit=$?"
exit=124
```

Exit 124 is `timeout` killing a program that never finished: each thread holds one account and waits for the other. Without the pause, the same binary hung in 1 of 200 runs in one batch and 7 of 200 in another. A test suite would call that a flaky timeout.

The fix gives every caller one global order. Locking the lower address first is the usual choice when accounts have no other stable key:

```
  struct account *first = from < to ? from : to;     /* one global order */
  struct account *second = from < to ? to : from;
  pthread_mutex_lock(&first->mu);
  if (pause_us) usleep(pause_us);
  pthread_mutex_lock(&second->mu);
```

With the same 100 ms pause, the fixed program prints `alice=95 bob=105` and exits 0, both without TSan and under TSan, which reports nothing.

## The disconfirming case: an outer lock that serializes both paths

Sometimes the inversion cannot turn into a deadlock. In this variant, every transfer goes through a wrapper that holds one ledger lock for the whole transfer:

```
static pthread_mutex_t ledger_mu = PTHREAD_MUTEX_INITIALIZER; /* held around every transfer */

static void locked_transfer(struct account *from, struct account *to, long amount) {
  pthread_mutex_lock(&ledger_mu);
  transfer(from, to, amount);
  pthread_mutex_unlock(&ledger_mu);
}
```

Two threads now cannot be inside `transfer` at the same time, so neither can hold one account lock while the other holds the second. The forced-timing run confirms it: `bank_gated.c`, run concurrently with the 100 ms pause and no TSan, prints `alice=95 bob=105` and exits 0.

TSan still reports the same cycle, exit 66. This run adds `TSAN_OPTIONS=second_deadlock_stack=1`, so each edge also shows where its first lock was taken:

```
WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock) (pid=5888)
  Cycle in lock order graph: M0 (0x...b78) => M1 (0x...ba8) => M0
  Mutex M1 acquired here while holding mutex M0 in thread T1:
    #1 transfer bank_gated.c:16:3
    #2 locked_transfer bank_gated.c:25:3
    #3 pay_bob bank_gated.c:29:48
  Mutex M0 previously acquired by the same thread here:
    #1 transfer bank_gated.c:14:3
    #2 locked_transfer bank_gated.c:25:3
  ...
```

The ledger lock does not appear anywhere in the report, and its presence did not stop the report. Here the report is a true description of the lock order and a false prediction of a deadlock. The dismissal rests on one fact that TSan cannot check: every path that takes two account locks holds `ledger_mu` first. In this file that is checkable, because `transfer` is `static` and `locked_transfer` is its only caller. If any other caller can reach `transfer` directly, the protection is gone.

If you dismiss on that basis, record the fact and the call-site check, and know what a suppression costs. The [suppressions page](https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions) lists a `deadlock` type that "suppresses lock inversion reports", matched against function and file names in the report's stack, and notes that "`*` is automatically prepended and appended to each suppression string." A file containing `deadlock:^transfer$` silences the gated program, exit 0. It also silences the original ungated `bank` binary, exit 0, because the suppression matches the function, not the reason it was safe. A later caller that skips the ledger lock would be hidden the same way. When the ordered fix is as small as the one above, apply it instead and keep the ledger lock for what it was meant to protect.

## Decide from the cycle and the call sites

| What the report says | Evidence to collect | Decision |
| --- | --- | --- |
| Cycle between two locks taken in caller-supplied order | A concurrent run with a forced pause between the two acquisitions | Fix with one global order, by address or a stable ID |
| Cycle between locks in two different functions | Both stacks per edge, from `second_deadlock_stack=1` | Fix the order in one function; document the order next to the locks |
| Cycle, but one outer lock is held on every path that takes both | Every call site of the inner acquisitions, and a forced-timing run that completes | Prefer the ordered fix; if you dismiss, record the call-site check, since a suppression also hides future ungated callers |
| Cycle with an outer lock on some paths only | The path that skips the outer lock | Fix |
| Report missing the first lock's stack | A rerun with `second_deadlock_stack=1` | Collect it before deciding |

The [guide to TSan reports involving code it cannot see](/learn/threadsanitizer-uninstrumented-code/) covers the data-race side of the same tool. A hang that shows up only sometimes in CI often looks like a flaky test first; the [guide to flaky test comments](/learn/ai-review-flaky-test-comment/) covers separating timing from logic.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Is a ThreadSanitizer race real when the synchronization is code TSan cannot see?](/learn/threadsanitizer-uninstrumented-code/)
    
    Code review The Proofline team November 25, 2026 5 min read
    
-   ### [A reviewer says your test is flaky: find the source first](/learn/ai-review-flaky-test-comment/)
    
    Code review The Proofline team November 22, 2026 4 min read
