Race conditions & mutexes
Find a data race and fix it with a correctly scoped mutex.
By Invicly Tech, , in Linux System Programming. About 12 minutes to read.
In short
A data race happens when threads access the same memory at the same time, at least one of them writes, and nothing synchronises them. Even counter++ is a read, an add and a write, so updates get lost. A mutex makes a critical section run one thread at a time.
Explained simply
Imagine two cashiers updating the same paper ledger. Both read "100", both add 10, both write "110". One sale vanished. That is a race condition: the result depends on the exact timing of two threads.
The fix is a lock. Before touching the ledger, a cashier takes the only pen. The other cashier must wait until the pen comes back. In code, the pen is a mutex (short for mutual exclusion). pthread_mutex_lock takes it, pthread_mutex_unlock gives it back.
The code between lock and unlock is the critical section. Keep it small: only the lines that touch the shared data. If a thread does slow work while holding the lock, every other thread just stands in line.
Races are sneaky. A racy program can pass tests a thousand times and fail on a busy server. So do not trust "it worked". Use ThreadSanitizer, a compiler option that watches memory accesses while the program runs and reports races with exact line numbers.
Press Play on a diagram to walk through it one step at a time.
- Thread A to counter in memory: read counter = 51read counter = 5
- Thread B to counter in memory: read counter = 52read counter = 5
- Thread A to counter in memory: write 63write 6
- Thread B to counter in memory: write 6: A's update is lost4write 6: A's update is lost
- Thread A to counter in memory: With a mutex: lock, read 6, write 7, unlock5With a mutex: lock, read 6, write 7, unlock
- Thread B to counter in memory: B waits for the lock, then reads 7, writes 86B waits for the lock, then reads 7, writes 8
- 1Reproduce
Stress test with many threads and loops
- 2Detect
Build with -fsanitize=thread and run
- 3Name the shared data
Read both stack traces in the report
- 4Guard every access
Same mutex for all reads and writes
- 5Verify
Rerun TSan and stress test until clean
- Back to step 1
In depth
Why counter++ breaks, even on one line
counter++ looks like one step, but the CPU does three: load the value into a register, add one, store it back. If two threads load the same old value, both store the same new value and one increment is lost. With two threads doing a million increments each, you often see a total like 1,2xx,xxx instead of 2,000,000.
The C standard goes further: a data race is undefined behaviour. The compiler may keep the value in a register for the whole loop, or merge stores, because it assumes no other thread is looking. That is why marking the variable volatile does not fix anything. volatile stops some optimisations, but it does not make the read-add-write a single step, and it does not order memory between threads. Only a lock or an atomic operation does.
- Race on a 64-bit counter: lost updates
- Race on a pointer or struct: torn or half-updated data, crashes
- volatile is for hardware registers and signal flags, not threads
What a mutex does under the hood
On Linux, a glibc mutex is a small integer in your memory plus the futex system call. Locking a free mutex is a single atomic compare-and-swap in user space: no system call, just tens of nanoseconds. Only when the mutex is already taken does the thread call futex to sleep in the kernel. Unlock sets the value back and, if someone is sleeping, calls futex to wake one waiter.
A mutex also gives memory ordering. Everything a thread wrote before unlock is visible to the next thread after its lock. That guarantee is what makes the data inside the critical section safe, not just the mutual exclusion. This is also why every access, including reads, must hold the lock: a reader without the lock gets no ordering guarantee.
- 1Try atomic swap 0 to 1
Done in user space, no syscall
- 2Success: you own it
Uncontended case, very cheap
- 3Already taken
Mark the mutex as having waiters
- 4futex wait
Thread sleeps in the kernel
- 5Owner unlocks
futex wake lets one waiter retry
Scoping locks: what to protect and for how long
Decide which data each mutex protects and write it down as a comment next to the data. A common, clean design puts the mutex inside the struct it guards, so the lock travels with the data.
Then keep critical sections short. Do the slow parts (file or network I/O, malloc of big buffers, formatting, sleeping) before taking the lock or after releasing it. A useful trick is copy-out: lock, copy the few fields you need into locals, unlock, then work on the copy.
Granularity is a trade-off. One big lock for everything is easy to get right but makes threads queue up. One lock per object lets threads work in parallel but brings the risk of deadlock when code needs two locks. Start coarse, measure contention with perf or by timing, then split only the hot lock.
- Simple to reason about
- No lock-ordering problems
- Threads wait on each other
- Good starting point
- Threads run in parallel
- More code and more memory
- Two locks can deadlock
- Use for proven hot spots
Mutex types and unlocking on every path
A mutex created with PTHREAD_MUTEX_INITIALIZER is the default type: locking it twice from the same thread hangs forever, and unlocking a mutex you do not own is undefined. While developing, an error-checking mutex helps: set PTHREAD_MUTEX_ERRORCHECK with pthread_mutexattr_settype, and a relock returns EDEADLK instead of hanging. A recursive mutex lets the owner lock again, but it usually hides a design problem.
The most common real bug is a forgotten unlock on an error path: return in the middle of a critical section and the next thread waits forever. Use a single exit point with goto out, or put the locked part in a small helper function that always unlocks before returning. Mutexes created with pthread_mutex_init should be released with pthread_mutex_destroy when no thread uses them any more.
- pthread_mutex_init(&m, NULL) for mutexes inside malloc'd structs
- ERRORCHECK type turns silent hangs into EDEADLK
- One exit label: lock, work, out: unlock, return
Finding races with ThreadSanitizer
ThreadSanitizer (TSan) is built into gcc and clang. Compile with -fsanitize=thread -g -O1 and run the program normally. TSan records which thread touched which memory and which locks it held. When two threads touch the same address without ordering and one of them writes, it prints WARNING: ThreadSanitizer: data race with both stack traces.
TSan finds races that actually happen in that run, so drive the code with a real workload or a stress test. It costs about 5 to 15 times slower execution and 5 to 10 times more memory, so use it in CI and testing, not in production. It cannot be combined with AddressSanitizer in the same build. valgrind --tool=helgrind is a slower alternative that needs no recompile.
- gcc -fsanitize=thread -g -O1 race.c -o race
- Run tests in a loop to make rare races show up
- Fix the race; do not add sleeps to hide it
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Reproduce a lost-update race~1h
- 2Protect shared data with a mutex~1h
- 3Keep critical sections short~1h
- 4Detect races with ThreadSanitizer~1h
Key points
- Every access to shared mutable data must hold the same mutex.
- Keep critical sections short and never do slow I/O while holding a lock.
- Unlock on every path, including error returns.
- ThreadSanitizer (-fsanitize=thread) reports data races at run time.
Key terms
Tap a card to flip it. 0/5 known
Examples
#include <pthread.h>
#include <stdio.h>
static long counter = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void *inc(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&lock); counter++; pthread_mutex_unlock(&lock);
}
return arg;
}
int main(void) {
pthread_t a, b; pthread_create(&a, NULL, inc, NULL); pthread_create(&b, NULL, inc, NULL);
pthread_join(a, NULL); pthread_join(b, NULL);
printf("%ld\n", counter); // always 2000000; without the lock it varies
}Remove the lock calls and compile with -fsanitize=thread to see the race reported.
Reading a ThreadSanitizer report
Take the explainer's counter program, remove the lock calls and build it with TSan. Step 1: compile with -fsanitize=thread and debug info. Step 2: run it. Step 3: read the report. It names the kind of access (write of size 8), the address, and the two threads with file and line. Both point at counter++ in inc, so counter is the shared data. Step 4: add the mutex back and rerun; the warning disappears and the total is always 2000000.
gcc -fsanitize=thread -g -O1 race.c -o race -pthread
./race
# WARNING: ThreadSanitizer: data race (pid=4242)
# Write of size 8 at 0x55d1c8e4b018 by thread T2:
# #0 inc race.c:7
# Previous write of size 8 at 0x55d1c8e4b018 by thread T1:
# #0 inc race.c:7
# Location is global 'counter' of size 8 at 0x55d1c8e4b018
# SUMMARY: ThreadSanitizer: data race race.c:7 in incShrinking a critical section with copy-out
A logger thread prints shared statistics every second. The first version held the lock while calling fprintf, so worker threads stalled whenever the disk was slow. Step 1: lock the mutex. Step 2: copy the struct into a local variable (a few bytes, fast). Step 3: unlock. Step 4: format and write the copy at leisure. Workers now wait for a memcpy, not for disk I/O.
#include <pthread.h>
#include <stdio.h>
struct stats {
pthread_mutex_t lock; /* protects all fields below */
long requests, errors, bytes;
};
void print_stats(struct stats *s, FILE *out) {
pthread_mutex_lock(&s->lock);
long req = s->requests, err = s->errors, bytes = s->bytes; /* copy out */
pthread_mutex_unlock(&s->lock);
fprintf(out, "req=%ld err=%ld bytes=%ld\n", req, err, bytes); /* slow part, no lock */
}Quick reference
- static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; for globals
- pthread_mutex_init(&s->m, NULL) and pthread_mutex_destroy for heap structs
- Every read and every write of shared data must hold the same mutex
- volatile does not make code thread-safe; use a mutex or C11 atomics
- Never do I/O, sleep or call unknown code while holding a lock
- gcc -fsanitize=thread -g -O1 finds races; not combinable with -fsanitize=address
- valgrind --tool=helgrind ./prog finds races without recompiling
- PTHREAD_MUTEX_ERRORCHECK makes a double lock return EDEADLK instead of hanging
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run the explainer's counter program without the lock 5 times and write down the totals. Then build it with -fsanitize=thread and find the line TSan reports.
- Exercise 2medium
Make a stack of ints safe for many threads: push and pop share one mutex, and pop returns 0 on success or -1 if the stack is empty. Unlock on every path.
- Exercise 3hard
Make the locked counter fast: 4 threads each do 10 million increments. Compare locking per increment with counting in a local variable and adding to the shared total once at the end. Time both.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need a mutex just to read a variable?
- Yes, if any other thread may write it at the same time. Without a lock or an atomic, the read is a data race and may see stale or half-written data.
- What is the difference between a mutex and a semaphore?
- A mutex has an owner and only that thread may unlock it; it guards data. A semaphore is a counter any thread can raise or lower, used to limit how many threads use a resource or to signal events.
- Is a spinlock better than a mutex?
- Rarely in user space. A spinlock burns CPU while waiting and does badly if the holder is descheduled. glibc mutexes already spin briefly in the cheap case, so use pthread_mutex_t unless you have measured otherwise.