c++multithreadingc++11atomichappens-before

Does modification order contribute to happens-before relationship?


// Thread 1
// do A
x.store(1, std::memory_order_release); // operation1

// Thread 2
// do B
x.store(2, std::memory_order_release); // operation2

// Thread 3
x.load(std::memory_order_acquire); // operation3

I've understood that if thread3 reads the value written by thread1, the release and acquire operations are synchronized-with, and effect of A is visible to thread3.
But what if the case is that:

Is there happens-before relationship between 1 and 3 ?
or intrinsically, does modification order contribute to happens-before relationship ?


Solution

  • No. there is no happens-before relationship between Operation 1 and Operation 3.

    From [atomics.order]/2:

    An atomic operation A that performs a release operation on an atomic object M synchronizes with an atomic operation B that performs an acquire operation on M and takes its value from any side effect in the release sequence headed by A.

    ... and unfortunately, Operation 2 is not in the release sequence headed by Operation 1 according to [intro.races]/5:

    A release sequence headed by a release operation A on an atomic object M is a maximal contiguous sub-sequence of side effects in the modification order of M, where the first operation is A, and every subsequent operation is an atomic read-modify-write operation.

    As a result, we cannot build any inter-thread happens-before relationship between Operation 1 and other operations, so there is no happens-before relationship between Operation 1 and Operation 3.