liveBook · Manning

Inter-thread ordering

As explained in C++ Concurrency in Action, Second Edition

The inter-thread happens-before relationship orders operations across threads through synchronization and sequencing rules.

Inter-thread happens-before orders operations across threads. If an operation in one thread synchronizes with an operation in another, the first happens-before the second; the relation is transitive and can combine with sequenced-before ordering within either thread. section 5.3.2

Ordering matters when threads access the same memory location:

  • Conflicting accesses—where at least one is a write—need defined ordering to avoid a data race and its undefined behavior. section 5.1.2
  • A shared mutex or atomic-operation synchronization can establish ordering; with multiple threads, every pair of accesses needs defined ordering. section 5.1.2
Listing 5.3. Order of evaluation of arguments to a function call is unspecified
#include <iostream>
void foo(int a,int b)
{
    std::cout<<a<<","<<b<<std::endl;
}
int get_num()
{
    static int i=0;
    return ++i;
}
int main()
{
    foo(get_num(),get_num());   #1
}

The function-call example illustrates a sequencing caveat: two get_num() calls used as arguments have unspecified evaluation order, distinguishing within-statement sequencing from inter-thread synchronization. section 5.3.2

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Defines inter-thread happens-before through synchronizes-with, transitivity, and composition with sequenced-before.
Examples
Contrasts sequencing with unspecified argument evaluation using two get_num() calls passed to foo().
What it assumes
Assumes familiarity with single-thread sequencing and distinguishes it from synchronization between threads.
What you can do after
Understand when conflicting cross-thread accesses are ordered and how mutexes or atomic synchronization establish that ordering.
How it connects
Connects happens-before to synchronizes-with, sequenced-before, mutexes, atomic operations, and data races.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.