Section 9.10

Happens-before relation

Definition

The happens-before relation is the order on a multithreaded program’s operations that a memory model, a language’s rules for which values reads may return, defines. Operation A happens before operation B if A precedes B in one thread or a chain of synchronizing operations links them. A non-atomic read returns the latest write to its variable that happens before it. Two accesses to one location from different threads, at least one a write and at least one not atomic, form a data race §9.3 if neither happens before the other.

The idea

A producer thread, one of several instruction sequences sharing one memory, fills an object and then raises a flag. A consumer thread sees the flag and reads the object. Suppose a log shows that the producer’s last write finished at 10:00:00.000001 and the consumer’s read started at 10:00:00.000005. That proves nothing about what the read returns. The write may still sit in the producer core’s store buffer, a queue of writes not yet visible to other cores, and the compiler may have moved the consumer’s read above its check of the flag. Order on a clock is not an order the memory model promises anything about.

The memory model builds its order out of program structure and synchronization instead. Inside one thread, program order counts. Between threads, only specific pairs of operations count: a release store and an acquire load that reads it, an unlock and the next lock of the same mutex §9.5, the creation of a thread and its first instruction. Chain such links, and everything before the start of the chain is visible after its end. The picture is a relay race: knowledge passes to the next runner only through the baton handoff, and a runner who never took the baton knows nothing of the earlier legs, however late that runner set off. The picture stops at one point: chains can branch and merge, so happens-before is a partial order §19.2.6, and many pairs of operations are not ordered either way.

How it works

C11 and C++11, the 2011 editions of the C and C++ standards [78, 247], build the relation from two kinds of link.

  1. Sequenced before. Within one thread, an evaluation that comes earlier in the program’s order of execution is sequenced before a later one.

  2. Synchronizes with. Between threads, certain pairs of operations create a link:

    • an atomic store with release order, or a stronger order, synchronizes with an atomic load of the same object with acquire order, or stronger, that reads the stored value, or a value written by a chain of read-modify-writes that follows the store;

    • each unlock of a mutex synchronizes with the next lock of the same mutex;

    • the completion of thrd_create synchronizes with the start of the new thread, and the end of a thread synchronizes with the return of thrd_join for that thread;

    • a release fence and an acquire fence, barrier operations that stand alone, can take the roles of the release store and the acquire load.

  3. Transitivity. If A happens before B and B happens before C, then A happens before C.

Leaving aside the consume ordering, which compilers implement as acquire, A happens before B exactly when a chain of sequenced-before and synchronizes-with links leads from A to B.

Three rules then use the relation.

The name comes from Leslie Lamport’s 1978 paper on distributed systems, which defined a happened-before relation between events in processes that communicate by messages [294]. The Java memory model has a relation of the same name with similar links: an unlock of a monitor happens before every later lock of it, and a write to a volatile field happens before every later read of that field. Tools such as ThreadSanitizer §10.25 detect data races at run time by tracking happens-before between the accesses they observe.

Worked example

Let payload be an ordinary int and ready an atomic_int, both 0 at the start. The producer runs payload = 42; (event WW) and then atomic_store_explicit(&ready, 1, memory_order_release); (event SS). The consumer runs r1 = atomic_load_explicit(&ready, memory_order_acquire); (event LL) and then, if r1 is 1, r2 = payload; (event RR).

Follow an execution in which LL reads 1.

  1. WW is sequenced before SS: same thread, WW first.

  2. SS synchronizes with LL: SS is a release store to ready, LL is an acquire load of ready, and LL read the value 1 that SS wrote.

  3. LL is sequenced before RR.

  4. By transitivity, WW happens before RR: three links give one derived relation.

  5. No other write to payload exists, so WW is the visible write for RR, and r2=42r2 = 42.

Now change one detail at a time.

Stated precisely

Let sb\mathrm{sb} be the sequenced-before relation and sw\mathrm{sw} the synchronizes-with relation, as listed above. Ignoring consume ordering, happens-before is the transitive closure hb=(sb∪sw)+,\mathrm{hb} = (\mathrm{sb} \cup \mathrm{sw})^{+}, which means that AhbBA \mathrel{\mathrm{hb}} B holds exactly when a chain A=X0,X1,…,Xn=BA = X_0, X_1, \ldots, X_n = B with n≥1n \ge 1 exists in which each consecutive pair is linked by sb\mathrm{sb} or sw\mathrm{sw}. In every execution the standard allows, hb\mathrm{hb} is a strict partial order: no operation happens before itself, and two operations may be unordered in both directions.

For an ordinary object MM and a read BB of MM, a write AA to MM is the visible write for BB when AhbBA \mathrel{\mathrm{hb}} B and no write XX to MM satisfies both AhbXA \mathrel{\mathrm{hb}} X and XhbBX \mathrel{\mathrm{hb}} B; then BB returns the value that AA wrote. An execution contains a data race when two conflicting accesses in different threads, at least one not atomic, are unordered by hb\mathrm{hb} in both directions, and a data race gives the program undefined behavior.

The conclusion of the example, WhbRW \mathrel{\mathrm{hb}} R and r2=42r2 = 42, rests on five conditions:

  1. ready is an atomic object, so the accesses to it never race;

  2. LL read the value that SS wrote, or one written by a chain of read-modify-writes that follows SS;

  3. SS is a release or stronger, and LL an acquire or stronger;

  4. no write to payload after SS is left unordered with RR;

  5. payload still exists when RR runs.

Limits and common mistakes

Happens-before is not time. AA happening before BB does not mean that AA finished earlier by any clock, and finishing earlier by a clock does not create happens-before.

Happens-before belongs to one execution. Suppose a flag starts at 0 and a producer is the only thread that stores 1. An acquire load that sees 1 reads the producer’s write. If two threads can store 1, the number alone no longer tells the reader which write it read.

For publication through one atomic object, an acquire can synchronize with the release whose value it reads or with the release that headed the sequence of writes from which it reads. It also orders earlier work already connected to that release by happens-before. Unrelated writes have no such guarantee.

Happens-before makes values visible; it does not keep objects alive. A field write that happens before a read of that field does not help if another thread frees the object first: the read is then a use-after-free §4.6.

Happens-before does not make several operations one. A check and a later update in one thread can both be well ordered and still let another thread act between them.

The volatile qualifier §4.34 creates no happens-before between threads in C or C++. In Java, volatile does.

Devices are outside the model. A DMA §4.36 (direct memory access) controller, hardware that copies memory without the processor, and a memory-mapped device register follow the processor architecture’s ordering rules and barrier instructions, not C’s happens-before.

Questions answered

Which synchronization operation establishes visibility of the published object’s fields?

A release store that publishes the object, paired with an acquire load that reads the published value, establishes the visibility: the release store synchronizes with that acquire load. The producer first initializes the fields, then stores the pointer or ready flag with release order (in C, atomic_store_explicit with memory_order_release). The consumer loads the same atomic variable with acquire order and checks that it read the published value before it touches the fields. The field writes are sequenced before the release in the producer’s thread, the release synchronizes with the acquire, and the field reads are sequenced after the acquire in the consumer’s thread. By transitivity of the happens-before relation, the order a memory model uses to decide which writes a read must see, every field write happens before every field read. Each read therefore returns the initialized value, provided that nobody writes the fields after publication.

Other operations create the same link: an unlock of a mutex after initialization and a lock of the same mutex before reading; sequentially consistent §9.12 stores and loads, which include release and acquire; a release fence before a relaxed store, paired with an acquire fence after a relaxed load that reads it; or creating the reader thread after initialization. A relaxed load alone, a volatile access, a barrier on one side only, or the fact that the read came later by a clock does not establish visibility.

Related entries: Data race (§9.3), Acquire-release ordering (§9.11), Coherent snapshot (§9.23), Memory barrier (§4.37), Mutex (§9.5). Further reading: [78, 79, 247, 294].