Imagine a movie theatre with exactly one seat left for the evening show. Two friends, sitting in different cities, open the booking app at the same moment. Both apps check the seat: "available". Both press Pay. Both get a confirmation. In the evening, two people arrive for one seat.
Nothing was wrong with either app on its own. The problem was that two activities read and changed the same shared data at the same time, and the final result depended on who did what first.
Inside a computer this happens all the time. In the earlier chapters we saw that the OS runs many processes and threads at once (Threads & Multithreading) and switches between them whenever the scheduler decides (CPU Scheduling Basics). The moment two of them share data, we have to think about synchronization. This chapter explains the problem: what a race condition is, why it happens even for something as tiny as count++, and why it is so hard to catch. The next few chapters build the solutions.
Independent vs Cooperating Processes
Processes (or threads) running at the same time come in two kinds:
Independent – it shares nothing with anyone else. Its result depends only on its own input. Running it at any speed, in any order with others, gives the same output.
Cooperating – it shares data with others (a global variable, a buffer in shared memory, a file, a database row). Others can affect it, and it can affect others.
Why cooperate at all? Because it is useful:
Information sharing – many users editing one document, many threads updating one cache.
Speed-up – split one big job across many CPU cores.
Modularity – a browser has separate threads for the network, rendering and the UI that pass data to each other.
Independent processes need no synchronization. Cooperating ones do, and that is what this whole part of the tutorial is about.
What Is Process Synchronization?
Process synchronization is the coordination of cooperating processes or threads so that they access shared data in a safe, controlled order, and the shared data always stays consistent no matter how the scheduler interleaves them.
Synchronization has two common goals:
Mutual exclusion – "only one at a time may touch this data". Example: only one thread updates the bank balance at once.
Ordering (condition synchronization) – "B must not start until A has finished". Example: a consumer must not read from a buffer until a producer has put something in it.
When synchronization is missing, we get race conditions.
What Is a Race Condition?
A race condition is a situation where several processes or threads access and modify shared data concurrently, and the final result depends on the particular order (timing) in which their instructions happen to execute.
The name comes from the idea that the threads are "racing" each other: whoever reaches a certain point first decides the outcome. Sometimes the answer is right, sometimes it is wrong, and you cannot predict which.
Let's see one for real.
A Real Race Condition in C
Two threads each add 1 to a shared counter one million times. The answer should obviously be two million.
#include <stdio.h>
#include <pthread.h>
#define N 1000000
long counter = 0; /* shared by both threads */
void *work(void *arg)
{
(void)arg;
for (int i = 0; i < N; i++)
counter++; /* read, add 1, write back */
return NULL;
}
int main(void)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, work, NULL);
pthread_create(&t2, NULL, work, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Expected: %d\n", 2 * N);
printf("Actual : %ld\n", counter);
return 0;
}Compiled and run three times on Linux (GCC, a 12-core machine):
$ gcc -std=c17 -Wall -pthread race.c -o race
$ ./race
Expected: 2000000
Actual : 1001553
$ ./race
Expected: 2000000
Actual : 1073942
$ ./race
Expected: 2000000
Actual : 1043597We lost close to a million increments (almost half of the work), and the answer is different on every run. The numbers you see on your machine will be different again, because they depend on timing. That randomness is the signature of a race condition.
How can counter++, one tiny line, go wrong?
Why counter++ Is Not One Step
To the programmer counter++ looks like a single operation. The CPU does not see it that way. Asking GCC for the x86-64 assembly of the loop body (with gcc -O0 -S) gives:
movq counter(%rip), %rax ; 1. LOAD counter from memory into register rax
addq $1, %rax ; 2. ADD 1 to the register
movq %rax, counter(%rip) ; 3. STORE the register back into memorySo counter++ is really three steps: load, add, store. Each thread has its own registers (they are saved in the thread's context, as we saw in Process Control Block & Context Switching), but counter lives in shared memory.
A thread can be interrupted between any two of these steps (a timer interrupt can arrive, or the scheduler can switch threads). On a multicore machine it is even simpler: both threads really run at the same instant on two cores.
A step-by-step trace of a lost update
Suppose counter = 5 and threads T1 and T2 each run counter++ once. Correct answer: 7.
Time | Thread T1 | Thread T2 | T1's register | T2's register | counter in memory |
|---|---|---|---|---|---|
1 | LOAD counter | 5 | – | 5 | |
2 | ADD 1 | 6 | – | 5 | |
3 | (preempted) | LOAD counter | 6 | 5 | 5 |
4 | ADD 1 | 6 | 6 | 5 | |
5 | STORE | 6 | 6 | 6 | |
6 | STORE | 6 | 6 | 6 |
Both threads did their increment, yet counter ends at 6, not 7. T1's store overwrote T2's work. This is called a lost update. Our C program suffered hundreds of thousands of these.
How many orders give the right answer?
Each thread runs 3 instructions, so there are 6! / (3! × 3!) = 20 possible interleavings that keep each thread's own order. We tried all 20 with a small Python simulation:
Experiment (start value 5) | Final values and how many of the 20 orders give each |
|---|---|
T1: | 7 → 2 orders, 6 → 18 orders |
T1: | 5 → 2 orders, 4 → 9 orders, 6 → 9 orders |
Only the 2 orders where one thread finishes all three steps before the other starts are correct. The other 18 are wrong. On a real machine the bad orders are rarer than this (because the three instructions usually run back-to-back), but with millions of iterations they happen often, as our program showed.
The second row is exactly the problem in the classic producer–consumer setup: a producer does count++ after putting an item in a shared buffer and a consumer does count-- after removing one. With count = 5, one of each should leave 5, but a race can leave 4 or 6, and now count no longer matches what is really in the buffer. We will solve that problem properly in Classical Synchronization Problems.
A Second Kind of Race: Check-Then-Act
Lost updates are not the only race. A very common pattern is check-then-act: you check a condition, then act on it, assuming the condition is still true. Between the check and the act, another thread can change things.
Here is the theatre-seat problem as a bank withdrawal. The balance is 1000 and two threads each try to withdraw 800. Only one of them should succeed.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int balance = 1000;
void *withdraw(void *arg)
{
int amount = *(int *)arg;
if (balance >= amount) { /* check */
sleep(1); /* pretend some slow work happens here */
balance = balance - amount; /* act */
printf("Withdrew %d\n", amount);
} else {
printf("Insufficient funds for %d\n", amount);
}
return NULL;
}
int main(void)
{
pthread_t a, b;
int amt = 800;
pthread_create(&a, NULL, withdraw, &amt);
pthread_create(&b, NULL, withdraw, &amt);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("Final balance: %d\n", balance);
return 0;
}$ gcc -std=c17 -Wall -pthread bank.c -o bank
$ ./bank
Withdrew 800
Withdrew 800
Final balance: -600Both threads passed the check balance >= 800 while the balance was still 1000, and both withdrew. The account is now −600. The sleep(1) just makes the gap between "check" and "act" large so the bug shows every time; in real code the gap is tiny, so the bug appears only once in a while, which is worse.
The same pattern appears everywhere:
Seat or ticket booking: "if seat is free, book it".
Creating a file: "if the file does not exist, create it". In security this is called TOCTOU (time-of-check to time-of-use), and attackers can exploit the gap.
Lazy initialisation: "if the object is not created yet, create it" (two threads may both create it).
Inventory: "if stock > 0, sell one".
The fix in every case is the same idea: the check and the act must happen as one indivisible unit, with no other thread allowed in between.
Where Can Race Conditions Happen?
Threads of one process – they share global variables and the heap, so any shared variable is at risk. This is the most common case.
Separate processes – normally their memory is private, but they can share a shared-memory segment, a memory-mapped file, a file on disk, or a database row (see Inter-Process Communication).
Inside the kernel – the kernel itself has shared data structures (the list of open files, the ready queue, memory allocation tables). Two CPUs running system calls at once, or an interrupt handler arriving in the middle of kernel code, can race. For example, if two processes call
fork()at the same time and the kernel did not protect its "next free PID" variable, both children could get the same PID.
An important point: you do not need multiple cores to get a race. On a single core, the timer interrupt can preempt a thread between the LOAD and the STORE, and another thread can run in that gap. Multiple cores just make it happen far more often.
Why Race Conditions Are So Hard to Find
They are non-deterministic. The program can pass a thousand tests and fail on the thousand-and-first, or fail only on the customer's faster machine.
Debugging changes the timing. Adding a
printfor running in a debugger slows things down, and the bug often disappears. Such bugs are nicknamed Heisenbugs.The compiler can hide them. When we compiled
race.cwith-O2, GCC turned the whole loop into a single "add 1000000" and the output became 2000000 every time. The bug was still there; it was just hidden for this exact program. Change the code a little and it comes back.The damage shows up later. A corrupted counter or linked list may crash the program minutes later in some unrelated function.
Real-world history has painful examples. The Therac-25 radiation therapy machine (1985–87) gave several patients massive overdoses partly because of a race condition between the operator's fast keyboard edits and the machine's setup software. The 2003 North American blackout was made worse by a race condition in an alarm system that silently stopped working. Concurrency bugs are not just exam topics.
Tools help: on Linux you can compile with gcc -fsanitize=thread (ThreadSanitizer) or run under valgrind --tool=helgrind. They watch memory accesses at runtime and report unsynchronized ones. But tools only find races in the code paths you actually run, so understanding the theory is still essential.
Race Condition vs Data Race
These two terms are often mixed up in interviews.
Data race | Race condition | |
|---|---|---|
Meaning | Two threads access the same memory location at the same time, at least one of them writes, and there is no synchronization between them. | The program's correctness depends on the timing or order of events. |
Level | Low-level, about individual memory accesses | High-level, about the program's logic |
Example | Our | Our bank example, even if each single read and write of |
In C/C++ | Undefined behaviour (the C11 standard says so) | A logic bug |
Most race conditions involve data races, but not all. If you made every individual read and write of balance atomic, the data race would be gone, yet two threads could still both pass the check before either subtracts. The check and the update together must be made indivisible.
The Key Idea: The Critical Section
Look at both bugs again. In each case there is a small piece of code that touches shared data:
counter++; // race.c
if (balance >= amount) // bank.c
balance = balance - amount;Such a piece of code is called a critical section. If we could guarantee that at most one thread is inside its critical section at any time, both bugs would disappear: every LOAD-ADD-STORE would finish before the next one begins, and nobody could sneak in between the check and the act.
That guarantee is called mutual exclusion, and providing it correctly, fairly and efficiently is the critical section problem. It is the subject of the next chapter, Critical Section Problem & Peterson's Solution.
Here is a roadmap of the tools we will build, from lowest level to highest:
Tool | Idea in one line | Chapter |
|---|---|---|
Peterson's solution | Pure software: two shared variables and careful ordering | Critical Section Problem & Peterson's Solution |
Hardware atomic instructions | The CPU does read-modify-write as one indivisible step (test-and-set, compare-and-swap) | Critical Section Problem & Peterson's Solution |
Mutex locks | Lock before the critical section, unlock after | Mutex Locks & Semaphores |
Semaphores | An integer counter with atomic | Mutex Locks & Semaphores |
Monitors | A language-level construct that does the locking for you, plus condition variables | Monitors |
As a teaser: the race in our counter program can be fixed in one line by using a C11 atomic variable, because x86 then uses a single lock addq instruction that the hardware performs indivisibly. We will run that version in the next chapter.
Common Mistakes and Misconceptions
"
x++is one instruction, so it is safe." It is load, add and store. Even when a CPU has a single "add to memory" instruction, it is not atomic across cores unless it uses a special atomic form (like x86'slockprefix)."Races only happen on multicore machines." Preemption on a single core is enough.
"My program gave the right answer, so it has no race." A race may show up once in a million runs. Correct output proves nothing; you need to reason about all interleavings.
"Only writes are dangerous; reads are fine." A reader can see a half-updated structure (for example, a linked list in the middle of an insert). Reads that race with writes are still bugs.
"Processes can never race because their memory is separate." They can, whenever they share a file, shared memory, or a database.
"
volatilefixes races in C." No.volatileonly stops the compiler from caching a variable in a register. It does not makex++atomic and does not stop the CPU from reordering memory operations.
Interview Questions
What is a race condition?
A situation where multiple processes or threads access shared data concurrently and the final result depends on the order in which their operations happen to execute. The output is unpredictable and can be wrong.
Why is count++ not thread-safe?
It compiles into three steps: load the value into a register, add one, store it back. If another thread runs between the load and the store, one of the updates is lost.
What is process synchronization? Why is it needed?
Coordinating cooperating processes or threads so that they access shared data in a controlled way. It is needed to prevent race conditions and keep shared data consistent, and to enforce ordering such as "consumer waits for producer".
Can a race condition occur on a single-core CPU?
Yes. The OS can preempt a thread in the middle of a read-modify-write sequence and run another thread that touches the same data.
What is the difference between a data race and a race condition?
A data race is an unsynchronized concurrent access to the same memory location where at least one access is a write. A race condition is a broader logic error where correctness depends on timing. Check-then-act bugs can be race conditions even without a data race.
Two threads each execute x++ 10 times on a shared x = 0 (load, add, store). What are the minimum and maximum possible final values?
Maximum 20 (no interference). Minimum 2, not 10. We confirmed this by enumerating every interleaving for 2, 3 and 4 increments per thread with a small Python script; the minimum was always 2. The trick: T1 loads 0, T2 does 9 full increments, T1 stores 1 (wiping out T2's work), T2 loads 1, T1 finishes all its remaining increments, and T2 finally stores 2.
What is a critical section?
The part of a program where it accesses shared resources (shared variables, files, buffers). To avoid races, at most one process or thread should execute its critical section for a given shared resource at a time.
How can you detect race conditions in practice?
Careful code review of shared data, stress testing with many threads, and dynamic tools such as ThreadSanitizer (-fsanitize=thread) or Helgrind, which report unsynchronized concurrent accesses.
Summary
Cooperating processes and threads share data; independent ones do not. Only cooperating ones need synchronization.
A race condition happens when the result depends on the timing of concurrent accesses to shared data.
counter++is really load, add, store. Interleaving these steps causes lost updates; our two-thread program lost almost half of its increments.Check-then-act code (booking, withdrawing, "create if missing") is another common source of races.
Races happen on single-core machines too, in user programs and inside the kernel, and they are hard to reproduce and debug.
The cure is to make the code that touches shared data, the critical section, run with mutual exclusion. How to do that correctly is the topic of Critical Section Problem & Peterson's Solution.