// 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:
x
is 1, 2Is there happens-before relationship between 1 and 3 ?
or intrinsically, does modification order contribute to happens-before relationship ?
If one action 'x' is visible to and ordered before another action 'y', then there is a happens-before relationship between the two actions indicated by hb(x, y). If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
Happens-before relationship is a guarantee that action performed by one thread is visible to another action in different thread. Happens-before defines a partial ordering on all actions within the program.
Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.
When the concept of multithreading is implemented, it is possible that changes made by one thread wouldn't be visible to the other thread. This indicates that the view of each thread is inconsistent with respect to each other. This is known as memory consistency error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With