Sub topic 4
Race conditions and interleavings
This chapter assumes you know what a process and a thread are, how a context switch works, and that the scheduler can preempt a running task between any two machine instructions. You should also be able to read C-like pseudocode.
What a race condition is
A race condition is a situation where the result of a program depends on the relative order in which operations from several processes or threads execute. The order is chosen by the scheduler, so it can change from run to run. The program is correct for some orders and wrong for others.
Two conditions must hold:
- Two or more activities access the same shared data. Shared memory, a file, or a database row all count.
- At least one of them writes, and the access is not protected by synchronisation.
If all activities only read, there is no race. If the data is private to each activity, there is no race.
Why `counter++` is not one step
A single C statement is usually several machine instructions. For counter++ on a load/store machine, the compiler emits something like this:
LOAD R1, countercopies the value from memory into a register.ADD R1, R1, 1increments the register.STORE counter, R1copies the register back to memory.
Each thread has its own registers, because a context switch saves and restores them. Memory is shared. The scheduler can switch threads between any two of these instructions, and that is the source of the problem.
An interleaving that loses an update
An interleaving is one particular merged order of the instruction streams of several threads. Within each thread the order is preserved. Across threads it can be anything.
Let counter = 5 and let threads T1 and T2 each run counter++ once.
| Step | Thread | Instruction | R1 of T1 | R1 of T2 | counter |
|---|---|---|---|---|---|
| 1 | T1 | LOAD | 5 | - | 5 |
| 2 | T2 | LOAD | 5 | 5 | 5 |
| 3 | T1 | ADD | 6 | 5 | 5 |
| 4 | T2 | ADD | 6 | 6 | 5 |
| 5 | T1 | STORE | 6 | 6 | 6 |
| 6 | T2 | STORE | 6 | 6 | 6 |
Two increments ran, but the counter went up by one. T2 overwrote T1's result using a stale value. This is called a lost update.
Counting interleavings and possible outcomes
GATE questions often ask for the possible final values. The method is to write each thread as a list of atomic steps and then reason about the interleavings.
If T1 and T2 each have 3 instructions, the number of interleavings is the number of ways to choose which 3 of the 6 slots belong to T1, which is C(6,3) = 20. Only two final values appear for one increment each:
- 7 appears when one thread's LOAD, ADD, STORE finishes before the other's LOAD. The two increments are effectively serial.
- 6 appears whenever both LOADs happen before either STORE. Both threads then write 6.
A serial execution always gives 7. Any outcome that no serial order could produce is a symptom of a race.
For larger loops the range widens. Suppose two threads each run counter++ N times, N at least 2, starting from 0. The maximum is 2N. The minimum is 2, not N. Here is a schedule for N = 2 that reaches it:
- T1 loads 0.
- T2 runs one full iteration, so the counter becomes 1.
- T1 stores 1.
- T2 loads 1.
- T1 runs its second iteration in full, so the counter becomes 2.
- T2 stores 2.
T2's last write comes from a register that was loaded before T1's final work, so almost everything is overwritten.
Seeing it run
This program starts two threads that each increment a shared counter one million times. Compile it with gcc race.c -o race -pthread and run it several times.
#include <pthread.h>
#include <stdio.h>
#define N 1000000
long counter = 0;
void *work(void *arg) {
(void)arg;
for (long i = 0; i < N; i++) {
counter++;
}
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, got %ld\n", 2 * N, counter);
return 0;
}On a multicore machine the result is usually below 2,000,000 and differs between runs. With optimisation enabled the compiler may keep counter in a register during the loop. That changes the numbers but does not remove the bug.
A mutex makes each increment indivisible with respect to the other thread:
#include <pthread.h>
#include <stdio.h>
#define N 1000000
long counter = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *work(void *arg) {
(void)arg;
for (long i = 0; i < N; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
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, got %ld\n", 2 * N, counter);
return 0;
}This now always prints 2,000,000. The region between lock and unlock is a critical section, which the next chapter defines.
Check-then-act races
Races are not limited to counters. A common pattern is to test a condition and then act on it, with a gap between the two.
if (balance >= amount) { /* check */
balance = balance - amount; /* act */
}Let balance = 100 and let two threads each withdraw 80. Both can pass the check before either subtracts. The balance then ends at 20 or at -60, depending on how the subtractions interleave. The invariant "balance never goes negative" was true at the check and false by the time of the action.
The same shape appears in other settings:
- Checking that a file does not exist and then creating it (a time-of-check to time-of-use bug).
- Taking an item from a queue after seeing that the queue is non-empty.
- Lazy initialisation, where two threads both see "not yet initialised" and both initialise.
Common mistakes
- Believing that a one-line statement is atomic.
counter++,x = x + y, andlist->count--are all multi-instruction. - Thinking the race needs a multicore CPU. On a single core, a timer interrupt can preempt a thread between LOAD and STORE, so the same bug appears.
- Concluding the code is safe because tests passed. A race can stay hidden for millions of runs because the bad window is a few instructions wide.
- Adding
sleepor a yield to "fix" timing. This only moves the window. Correctness must not depend on timing. - Assuming reads are always safe. A reader can see a half-updated structure while a writer is mid-update.
How to analyse a code fragment in an exam
- Mark every shared variable and every access to it.
- Split each statement that touches shared data into its load, compute, and store steps.
- Look for a pair of accesses, at least one a write, that can happen in different threads with no ordering enforced between them.
- Build one interleaving that gives a result no serial order can give. That interleaving is the proof of a race.
- If the question asks for all possible results, enumerate the serial orders first, then add the overlapping ones.
The fix is to forbid the harmful interleavings by making the access sequence a critical section. That problem and its requirements are the subject of the next chapters.
Exercise
Shared variable x starts at 0. Thread A runs "x = x + 1" once and thread B runs "x = x + 2" once. Each statement compiles to LOAD, ADD, STORE. List every possible final value of x and give one interleaving for each.
Show answer
The possible final values are 1, 2 and 3. For 3, run the threads serially, A then B or B then A. For 1, run A.LOAD (reads 0), B.LOAD (reads 0), B.ADD, B.STORE (x = 2), A.ADD, A.STORE, which writes 1 and overwrites B's result. For 2, run A.LOAD, B.LOAD, A.ADD, A.STORE (x = 1), B.ADD, B.STORE, which writes 2 and overwrites A's result.
Exercise
Two threads each execute "counter++" in a loop of 2 iterations, starting from counter = 0. What are the largest and smallest possible final values?
Show answer
The largest is 4, reached when no update is lost. The smallest is 2. Schedule: T1 loads 0. T2 completes one iteration, so counter is 1. T1 stores 1. T2 loads 1. T1 completes its second iteration, so counter is 2. T2 stores 2.