Skip to content
systemcoding.dev
Concurrency

What Is a Race Condition and How Mutexes Prevent It

A race condition is a bug where the result depends on thread timing. See a lost-update counter in C with pthreads and how a mutex makes the update atomic.

6 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the C, C++ and Erlang logos.

Two threads each add one to a shared counter a million times. You expect two million. You get 1,184,302 on one run and 1,391,877 on the next. Nothing crashed, no warning appeared, and the answer is simply wrong in a different way each time. That is a race condition, and it is the first bug every concurrent program meets. This post explains what happens at the machine level, shows the bug in C with POSIX threads on Linux with glibc 2.41 and GCC 14, and fixes it with a mutex. Once you understand why counter++ is not one step, locks stop feeling like ceremony. For the full tour of locks, condition variables and their alternatives, see the cornerstone guide on mutexes, condition variables and locks.

What a race condition is

A race condition exists when the correctness of a program depends on the relative timing of operations in two or more threads. The most common form is a data race as defined by the C11 standard: two threads access the same memory location, at least one access is a write, and nothing orders them. C11 and C++11 say a program with a data race has undefined behavior, which means the compiler is allowed to assume it never happens and optimize on that assumption.

Not every race condition is a data race, and not every data race produces a visible wrong answer on your machine. But the combination of "usually works" and "occasionally wrong" is what makes these bugs expensive. A test passes a thousand times and fails in production under load.

Why counter++ is three steps

The source line counter++ looks like one operation. The processor sees it as three: load the value from memory into a register, add one, store the register back. On x86-64, GCC at -O0 typically compiles it to a mov from memory, an add, and a mov back to memory. At higher optimization levels it may become a single add instruction with a memory operand, but even then the processor performs a read, a modify and a write internally, and a plain add to memory is not atomic across cores without the lock prefix.

Now interleave two threads. Both load the counter as 5. Both add one to get 6. Both store 6. Two increments happened and the counter went up by one. That is a lost update.

StepThread AThread BMemory
1load 55
2load 55
3add, 6add, 65
4store 66
5store 66

The window in which this can happen is tiny for one increment and huge across two million, which is why the error shows up as a count that is short by thousands rather than by one.

The bug in C

Here is the smallest complete program that shows it. It creates two threads, each of which increments a global counter one million times.

race.cc
#include <pthread.h>
#include <stdio.h>

#define N 1000000

static long counter = 0;

static void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < N; i++) {
        counter++;
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, work, NULL);
    pthread_create(&b, NULL, work, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("counter = %ld (expected %d)\n", counter, 2 * N);
    return 0;
}

Build and run it with gcc -O1 -pthread race.c -o race && ./race:

Text
counter = 1184302 (expected 2000000)

The exact number will differ on every run and on every machine, so treat the digits as an example. What does not vary is that the result is below two million, and that is the signature of a lost update. On a single-core machine with a short loop you might see 2000000 by luck, because the scheduler rarely preempts a thread mid-increment. That is not a pass. It is the same bug waiting for more cores.

Fix it with a mutex

A mutex, short for mutual exclusion, is a lock with two operations: lock and unlock. At most one thread holds it at a time. Any other thread that calls lock while it is held blocks until the holder unlocks. Code between lock and unlock is called a critical section, and while a thread is inside it no other thread can be inside a critical section protected by the same mutex.

POSIX gives you pthread_mutex_t, defined in <pthread.h>. A statically allocated mutex can be initialized with the constant PTHREAD_MUTEX_INITIALIZER, as the POSIX.1-2024 specification of pthread_mutex_init describes.

race_fixed.cc
#include <pthread.h>
#include <stdio.h>

#define N 1000000

static long counter = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < N; i++) {
        pthread_mutex_lock(&lock);
        counter++;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, work, NULL);
    pthread_create(&b, NULL, work, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("counter = %ld (expected %d)\n", counter, 2 * N);
    return 0;
}
Text
counter = 2000000 (expected 2000000)

Every increment now sits between a lock and an unlock, so the three machine steps of one increment finish before the other thread's three begin. The result is deterministic: it is always 2000000.

A mutex does two jobs, and the second is the one beginners miss. Besides excluding other threads, pthread_mutex_unlock followed by another thread's pthread_mutex_lock makes the first thread's writes visible to the second. POSIX lists these functions among those that synchronize memory with respect to other threads. Without it, the compiler could keep counter in a register across iterations, and the processor could delay the store. The lock is what makes the shared value coherent, not only exclusive.

What the lock costs

Taking the lock a million times has a price. An uncontended lock is cheap, but when two threads hammer the same mutex, one often sleeps while the other works, and the waking costs a system call. The fixed program is correct and slower than the broken one. Do not read that as a reason to skip locking. Read it as a reason to lock less often: if each thread kept a private count and added it to the shared total once at the end, there would be only two lock acquisitions in the whole run.

race_local.cc
static void *work(void *arg) {
    (void)arg;
    long local = 0;
    for (int i = 0; i < N; i++) {
        local++;
    }
    pthread_mutex_lock(&lock);
    counter += local;
    pthread_mutex_unlock(&lock);
    return NULL;
}

This version has the same output and is the pattern to reach for when threads accumulate results. Keep critical sections short and put as little as possible inside them.

Finding races you cannot see

You will not always get a wrong number to tell you. ThreadSanitizer, built into GCC and Clang with -fsanitize=thread, instruments memory accesses at run time and reports a data race the first time two unordered accesses happen, even when the value comes out right. Compile race.c with gcc -g -fsanitize=thread -pthread race.c and it prints a warning that begins with WARNING: ThreadSanitizer: data race, naming both threads and the lines involved. Make that part of your test build for any threaded code. The GCC manual documents the option under its instrumentation flags.

Where a mutex is not the answer

For a single shared counter, C11 gives you atomic_fetch_add from <stdatomic.h>, which does the whole read-modify-write as one indivisible step with no lock object. Use it when the shared state is one machine word and you need nothing else to be consistent with it. Once two variables must change together, such as a balance and a transaction count, atomics on each do not keep them consistent, and a mutex around both is the right tool.

A mutex also does not fix an ordering problem. If one thread must wait until another has produced something, a mutex alone makes you poll. That is what condition variables are for, and they come next in this cluster.

Taggedcbeginner
Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.