Sub topic 4
Race Conditions and Interleavings
Prerequisites
This chapter assumes that you understand processes, threads, shared memory, context switches, and CPU scheduling. You should also be comfortable reading C-like pseudocode.
What Is a Race Condition?
A race condition occurs when the result of a program depends on the timing or order of concurrent operations. Two processes or threads race because the scheduler may interleave their instructions in different ways.
Consider two threads that share counter:
#include <pthread.h>
#include <stdio.h>
int counter = 0;
void *increment(void *arg) {
for (int i = 0; i < 100000; i++)
counter = counter + 1;
return NULL;
}
int main(void) {
pthread_t first, second;
pthread_create(&first, NULL, increment, NULL);
pthread_create(&second, NULL, increment, NULL);
pthread_join(first, NULL);
pthread_join(second, NULL);
printf("counter = %d\n", counter);
return 0;
}The intended result is 200000. However, counter = counter + 1 is not one indivisible operation. It usually contains these steps:
- Read
counter. - Add one to the value.
- Write the result back.
Suppose counter is initially 0:
| Thread 1 | Thread 2 | Value |
|---|---|---|
| Reads `0` | 0 | |
| Reads `0` | 0 | |
| Computes `1` | 0 | |
| Computes `1` | 0 | |
| Writes `1` | 1 | |
| Writes `1` | 1 |
Two increments occurred, but the final value is 1. The updates were lost.
In standard C, this unsynchronised access is a data race and gives undefined behavior. The example is useful because it exposes the underlying interleaving, but a real program must protect the shared variable with a mutex or an atomic operation.
Interleavings
An interleaving is a sequence formed by taking steps from multiple threads while preserving the order within each thread. The scheduler can switch threads between instructions, including between a read and a write.
A race condition requires more than concurrency. The operations must access shared state, at least one operation must modify that state, and the accesses must lack sufficient synchronisation.
Finding the Wrong Interleaving
To analyse a concurrent program:
- Break each shared-data statement into smaller reads, computations, and writes.
- Preserve each thread's internal order.
- Interleave steps from different threads.
- Look for an execution that violates the expected result.
- Identify the critical section: the code that must not overlap with another access.
Exercise
Two threads each execute x = x + 1 once, and x starts at 5. What final values are possible under the usual read-compute-write model?
Show answer
The final value can be 6 or 7. It is 7 when the increments occur without overlapping. It is 6 when both threads read 5 before either writes.