DATA RACE
counter++ is three instructions, not one
Two threads each run counter++ exactly once, starting from counter = 0. Which final values are possible?
Two threads read a shared variable, increment locally, write back. With no synchronization, the reads can both see the same old value and one increment is lost. The bug is below the level of the source: counter++ compiles to load, add, store, and the scheduler can switch threads between any two of them.
That is a data race: two threads touch the same memory, at least one of them writes, and nothing orders the accesses. The sim uses a simple load, add, store model, where the outcomes are 1 or 2. In C and C++ the language says a data race is undefined behaviour, so the compiler is allowed to produce stranger results than that.
// Thread A and B both run:
int tmp = counter; // load
tmp = tmp + 1; // add
counter = tmp; // store// Atomic increment — one indivisible op.
atomic_fetch_add(&counter, 1);
// or under a mutex:
pthread_mutex_lock(&m);
counter++;
pthread_mutex_unlock(&m); The invariant strip tracks two things: counter == increments completed, and that at most one thread is between its load and its store. In LOST UPDATE the second goes red as soon as both threads have loaded, before anything is visibly wrong; the first goes red on the last store. Both stay green in the fixes even though the threads still interleave.
Both threads must run all three of their steps. Order them so that one increment disappears.
GOAL: both threads finish and counter == 1
Rewrite increment so two threads calling it concurrently always add exactly 2. The grader tries every interleaving of the two threads’ memory operations.
Counters, metrics, inventory decrements, balance updates, any x = x + 1 on shared memory or a shared database row without a transaction. Symptoms are statistical: totals that drift, never a crash.
“Why is this counter wrong?” and “How would you make it thread-safe?” Name both fix families, say which you would pick and why (atomics for a single word, a lock for multi-field updates), and mention that the race window is tiny so tests will not catch it.
USED IN
Chapters that build on this lesson.
- Test automation and the SDETQA and Quality Engineering
- Test data, environments and flaky testsQA and Quality Engineering
- Testing time, randomness and concurrencySoftware Testing and Quality