Operating Systems Module 4: Concurrency Lesson 4.1 14 min

Race conditions

count++ looks like one step but is three. If two threads interleave those steps badly, an update vanishes, and nothing reports an error.

Two threads each add 1 to the same counter. You run the program and the counter says 2. You run it a thousand times and it says 2 every time, until the day it says 1. Nothing crashed, nothing printed an error, and you cannot make it happen again. What went wrong?

The answer is in the line you thought was a single step. In Lesson 2.4 you saw that threads share memory. This lesson is the price of that sharing.

One line, three instructions

In C (and in most languages) you write count = count + 1. A CPU cannot add to a number in memory in one go, so the compiler turns that line into three instructions:

  1. load r, count: copy the value of count from memory into a register.
  2. add r, 1: add 1 to the register.
  3. store count, r: copy the register back into memory.

Each thread has its own registers (Lesson 2.4), so each has its own r. But count is one box in memory, shared by both. And the kernel can switch from one thread to another between any two instructions (Lesson 2.5).

First, a friendly schedule. Thread A runs all three instructions, then thread B runs all three. Watch count.

Thread A, then thread B

  1. Start: count is 0 The shared variable count holds 0. 2 threads each run count = count + 1. The compiler turns that one line into three instructions, and the CPU can switch threads between any two of them.
    count (shared)
    0
    A: r
    –
    B: r
    –
    Updates lost
    0
  2. A loads count A copies count into its own register: r = 0. count itself has not changed, and the copy is private to A.
    count (shared)
    0
    A: r
    0
    B: r
    –
    Updates lost
    0
  3. A adds 1 A adds 1 to its register: r = 1. This happens only in A's register. count has not been touched.
    count (shared)
    0
    A: r
    1
    B: r
    –
    Updates lost
    0
  4. A stores count A writes r = 1 back into count. Nobody changed count since A loaded it, so this update is kept.
    count (shared)
    1
    A: r
    1
    B: r
    –
    Updates lost
    0
  5. B loads count B copies count into its own register: r = 1. count itself has not changed, and the copy is private to B.
    count (shared)
    1
    A: r
    1
    B: r
    1
    Updates lost
    0
  6. B adds 1 B adds 1 to its register: r = 2. This happens only in B's register. count has not been touched.
    count (shared)
    1
    A: r
    1
    B: r
    2
    Updates lost
    0
  7. B stores count B writes r = 2 back into count. Nobody changed count since B loaded it, so this update is kept.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Updates lost
    0
  8. Finished: count is 2 Every thread finished and count is 2, which is what 2 increments should give. Nothing was lost this time. The schedule happened to keep each increment in one piece, but nothing forced it to.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Updates lost
    0

Each thread did its three steps without being interrupted, so the second thread started from the first one’s result. The answer is correct. But nothing in the program made that happen: the scheduler was just kind.

The unlucky interleaving

Now the same two threads, with the instructions interleaved: A, B, A, B, A, B. The kernel switches threads after every instruction.

The two threads take turns

  1. Start: count is 0 The shared variable count holds 0. 2 threads each run count = count + 1. The compiler turns that one line into three instructions, and the CPU can switch threads between any two of them.
    count (shared)
    0
    A: r
    –
    B: r
    –
    Updates lost
    0
  2. A loads count A copies count into its own register: r = 0. count itself has not changed, and the copy is private to A.
    count (shared)
    0
    A: r
    0
    B: r
    –
    Updates lost
    0
  3. B loads count B copies count into its own register: r = 0. count itself has not changed, and the copy is private to B. A also holds a copy taken earlier. Everyone is working from a number that may soon be out of date.
    count (shared)
    0
    A: r
    0
    B: r
    0
    Updates lost
    0
  4. A adds 1 A adds 1 to its register: r = 1. This happens only in A's register. count has not been touched.
    count (shared)
    0
    A: r
    1
    B: r
    0
    Updates lost
    0
  5. B adds 1 B adds 1 to its register: r = 1. This happens only in B's register. count has not been touched.
    count (shared)
    0
    A: r
    1
    B: r
    1
    Updates lost
    0
  6. A stores count A writes r = 1 back into count. Nobody changed count since A loaded it, so this update is kept.
    count (shared)
    1
    A: r
    1
    B: r
    1
    Updates lost
    0
  7. B stores, and an update is lost B loaded count when it was 0, but by now it is 1. Storing r = 1 puts back a number built from the old value, and the change made in between disappears. This is a lost update.
    count (shared)
    1
    A: r
    1
    B: r
    1
    Updates lost
    1
  8. Finished: count is 1, not 2 Every thread finished, and 2 increments ran, so count should be 2. It is 1: 1 update was lost, and nothing reported an error. The answer depends on how the threads happened to interleave.
    count (shared)
    1
    A: r
    1
    B: r
    1
    Updates lost
    1

Two increments, and count went up by one. An update was lost. The program did exactly what it was told. The bug is that the three instructions were not kept together.

The memory view shows the same run as a list of accesses to count. Notice the two reads of the same old value, which are the root of the problem.

Try to break it yourself

This challenge starts from the friendly schedule. Open Try it. In the first box you decide who runs each instruction, one letter per instruction, in order. Write six letters, three A and three B, and press Run. Your goal: make an update get lost. If you cannot, think about what has to happen between A’s load and A’s store.

Your turn: lose an update

  1. Start: count is 0 The shared variable count holds 0. 2 threads each run count = count + 1. The compiler turns that one line into three instructions, and the CPU can switch threads between any two of them.
    count (shared)
    0
    A: r
    –
    B: r
    –
    Updates lost
    0
  2. A loads count A copies count into its own register: r = 0. count itself has not changed, and the copy is private to A.
    count (shared)
    0
    A: r
    0
    B: r
    –
    Updates lost
    0
  3. A adds 1 A adds 1 to its register: r = 1. This happens only in A's register. count has not been touched.
    count (shared)
    0
    A: r
    1
    B: r
    –
    Updates lost
    0
  4. A stores count A writes r = 1 back into count. Nobody changed count since A loaded it, so this update is kept.
    count (shared)
    1
    A: r
    1
    B: r
    –
    Updates lost
    0
  5. B loads count B copies count into its own register: r = 1. count itself has not changed, and the copy is private to B.
    count (shared)
    1
    A: r
    1
    B: r
    1
    Updates lost
    0
  6. B adds 1 B adds 1 to its register: r = 2. This happens only in B's register. count has not been touched.
    count (shared)
    1
    A: r
    1
    B: r
    2
    Updates lost
    0
  7. B stores count B writes r = 2 back into count. Nobody changed count since B loaded it, so this update is kept.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Updates lost
    0
  8. Finished: count is 2 Every thread finished and count is 2, which is what 2 increments should give. Nothing was lost this time. The schedule happened to keep each increment in one piece, but nothing forced it to.
    count (shared)
    2
    A: r
    1
    B: r
    2
    Updates lost
    0

Hint. B has to load count while A is still holding the old value in a register, that is, after A’s load but before A’s store. For example A B A B A B does it, and so do many others. Try A A B A B B, or B A B A A B, and see which ones fail.

You will find that most mixed schedules lose an update, and only a few are safe. Real schedulers pick the interleaving, not you, and it changes from run to run.

Critical sections

The three instructions that read and write the shared variable form a critical section: a stretch of code that must not be run by two threads at the same time. If the two threads’ critical sections overlap, the result can be wrong. The rule that fixes this is mutual exclusion: at most one thread inside the critical section at a time.

A bug where the outcome depends on the timing of threads is a race condition (or data race). The name comes from the picture: two threads race to the shared variable and whoever gets there first decides the result.

Race conditions are some of the nastiest bugs in programming, for three reasons. They only appear for some interleavings, so the program can pass every test. The code that is wrong looks innocent. And adding a printf or a debugger changes the timing, so the bug can disappear when you look for it.

It happens in real C programs

This program starts two threads, and each adds 1 to a shared counter a million times. The counter is volatile so that the compiler really does a load and a store each time, as in the simulator, instead of keeping the value in a register for the whole loop.

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

volatile long counter = 0;              /* shared by both threads */

void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < 1000000; i++)
        counter++;                      /* load, add, store: not one step */
    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 (two threads added 1,000,000 each)\n", counter);
    return 0;
}

Output (one run)

counter = 1044489 (two threads added 1,000,000 each)

Two million increments were requested, so a correct program prints 2000000. The number you see is usually less than 2000000, and it is different each time you run it. If your computer has only one core, you may be lucky more often, but the bug is still there. Every missing increment is a lost update like the one you just made by hand.

In the real world

Race conditions have caused real harm. The Therac-25 radiation machine in the 1980s had a race in its control software that, in rare timings, gave patients massive overdoses. Web shops have sold the last item twice, and banks have paid out one balance twice, for the same reason.

Tools can help find them. On Linux, compile with -fsanitize=thread and run the program: ThreadSanitizer watches memory accesses and reports data races, even in runs where the answer happened to come out right. Languages can help too: Rust’s ownership rules refuse to compile many races, as you may remember from Rust from Zero.

Quick check

Quick check

  1. Why is count = count + 1 not safe when two threads run it on a shared variable?
  2. Two threads each add 1 to a counter that starts at 0, and it ends at 1. What happened?
  3. Why is a race condition hard to reproduce?
  4. What does mutual exclusion mean?

Recap

  • count = count + 1 is three instructions: load, add, store. The kernel can switch threads between any two of them.
  • If two threads both load before either stores, one update is lost, with no error message.
  • A bug whose result depends on thread timing is a race condition. It can hide for a long time.
  • The code that touches shared data is a critical section. Mutual exclusion means only one thread inside at a time.

Next: how do you make the critical section one-at-a-time? With a lock, and the lock itself needs help from the hardware.

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion