Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple readers synchronize with the same writers with acquire/release ordering?

After reading "Concurrency in action" I could not find an answer to one question - are there guarantees in the standard for reading side effects when we have one store(release) and many loads(acquire) on one atomic variable? Suppose we have:

int i{};
atomic<bool> b{};

void writer(){
 i=42;
 b.store(true,memory_order_release);
}

void reader(){
 while(!b.load(memory_order_acquire))
    this_thread::yield();
 assert(i==42);
}
//---------------------
thread t1{writer},t2{reader},t3{reader};

If we had only one reader, all ok, but can we have failed assertion in t2 or t3 thread?

like image 356
Despise Avatar asked Dec 14 '25 10:12

Despise


1 Answers

This is a text-book example of a happens-before relationship between the store to i in writer and the load from i in both reader threads.

That multiple readers are involved does not matter. The store to b synchronizes with all readers that observe the updated value (which will eventually happen thanks to the loop).

I think the quote you're looking for is:

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.

It does not say that this is limited to a single load operation

like image 118
LWimsey Avatar answered Dec 16 '25 03:12

LWimsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!