Skip to content

Lesson 2 of 9 · 24m

Threads, Interleavings, and Happens-Before

The mental model that explains data races: operations interleave, compilers and CPUs reorder memory access, and only happens-before relationships make visibility predictable.

The nasty part of concurrency is that your program does not execute the statements in the order you wrote them, and other threads do not necessarily see the order you executed. Hardware reorders memory operations for performance. Compilers reorder instructions for optimization. CPUs cache values locally. The result is correct-looking code that fails once every million runs.

A data race is not just a wrong answer

Consider two threads incrementing the same counter in C++:

int counter = 0;
void worker() {
    for (int i = 0; i < 100000; ++i) {
        counter++;  // read-modify-write, not atomic
    }
}

counter++ compiles to a load, an increment, and a store. Two threads can both load the same value, increment their private copies, and store the same result. You expect 200000 and can get almost anything lower. Worse: in C and C++, an unsynchronized read/write race is undefined behavior, so the compiler is allowed to optimize as if it cannot happen.

Visibility is the harder half of the problem

Even if each operation were atomic, one thread may not observe another thread's write promptly — or ever:

bool ready = false;
int payload = 0;
// thread 1
payload = 42;
ready = true;
// thread 2
while (!ready) { }
assert(payload == 42);  // not guaranteed without synchronization

Thread 2 can see ready == true before it sees payload == 42, because the two writes can become visible in different orders. This is not exotic hardware behavior; it is the standard memory model working as designed.

Happens-before is the contract

A write is guaranteed visible to a read when there is a happens-before edge between them. You create those edges with synchronization:

  • unlocking a mutex happens-before the next successful lock of that mutex
  • an atomic release store happens-before an acquire load that observes it
  • thread creation happens-before the new thread starts
  • a thread finishing happens-before a successful join Everything else is unspecified ordering. Your job is not to mentally simulate every CPU. Your job is to establish enough happens-before edges that the required order is guaranteed.

Safe publication is a pattern, not luck

The fixed version uses atomics with the right ordering:

std::atomic<bool> ready{false};
int payload = 0;
// producer
payload = 42;
ready.store(true, std::memory_order_release);
// consumer
if (ready.load(std::memory_order_acquire)) {
    assert(payload == 42);  // release/acquire publishes the payload write
}

The release store says: everything I wrote before this point becomes visible before this flag. The acquire load says: if I observe the flag, I also observe everything the writer published.

Field notes

  • Volatile is not synchronization, and a passing test often means only that the timing never exposed the missing edge.
  • Joining a thread is synchronization; never reason from assembly alone — compiler, cache coherence, and the language memory model all matter.
  • If two threads touch the same memory and at least one writes, you need a synchronization story. No story means a bug.

Was this lesson helpful?

Sign in to rate