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.
Sequenced before. Within one thread, an evaluation that comes earlier in the program’s order of execution is sequenced before a later one.
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_createsynchronizes with the start of the new thread, and the end of a thread synchronizes with the return ofthrd_joinfor 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.
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.
Visibility. A read of an ordinary, non-atomic object returns the value of its visible write: the write to that object that happens before the read, with no other write to the object between them in happens-before.
Data race. Two accesses conflict if they touch the same memory location and at least one of them writes. Conflicting accesses in different threads, at least one not atomic, neither of which happens before the other, form a data race. The program then has undefined behavior §4.12: the standard sets no requirement on what it does.
Coherence. For an atomic object, a read never returns a value older, in the object’s single order of writes, than a write that happens before the read.
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 ) and then atomic_store_explicit(&ready, 1, memory_order_release); (event ). The consumer runs r1 = atomic_load_explicit(&ready, memory_order_acquire); (event ) and then, if r1 is 1, r2 = payload; (event ).
Follow an execution in which reads 1.
is sequenced before : same thread, first.
synchronizes with : is a release store to
ready, is an acquire load ofready, and read the value 1 that wrote.is sequenced before .
By transitivity, happens before : three links give one derived relation.
No other write to
payloadexists, so is the visible write for , and .
Now change one detail at a time.
If reads 0, no synchronizes-with link exists, and the consumer does not read
payload. The check ofr1is part of the protocol for this reason.If uses
memory_order_relaxed, can still read 1, but a relaxed load is not an acquire, so does not synchronize with . and are then conflicting non-atomic accesses in different threads with no happens-before between them: a data race. The execution has undefined behavior; it does not merely risk .If the producer wrote
payloadat 1 microsecond and the consumer read it at 5 microseconds by a common clock, with no synchronization at all, the clock order changes nothing. and are still unordered, and the program still has a data race.
Stated precisely
Let be the sequenced-before relation and the synchronizes-with relation, as listed above. Ignoring consume ordering, happens-before is the transitive closure which means that holds exactly when a chain with exists in which each consecutive pair is linked by or . In every execution the standard allows, is a strict partial order: no operation happens before itself, and two operations may be unordered in both directions.
For an ordinary object and a read of , a write to is the visible write for when and no write to satisfies both and ; then returns the value that wrote. An execution contains a data race when two conflicting accesses in different threads, at least one not atomic, are unordered by in both directions, and a data race gives the program undefined behavior.
The conclusion of the example, and , rests on five conditions:
readyis an atomic object, so the accesses to it never race;read the value that wrote, or one written by a chain of read-modify-writes that follows ;
is a release or stronger, and an acquire or stronger;
no write to
payloadafter is left unordered with ;payloadstill exists when runs.
Limits and common mistakes
Happens-before is not time. happening before does not mean that 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].