std atomic synchronisation and non atomic variable : not a stale data?

Viewed 154

I know that this code is correct (except the delete not done) :

#include <thread>
#include <atomic>
#include <cassert>
#include <string>

std::atomic<std::string*> ptr;
int data;

void producer()
{
    std::string* p  = new std::string("Hello");
    data = 42;
    ptr.store(p, std::memory_order_release);
}

void consumer()
{
    std::string* p2;
    while (!(p2 = ptr.load(std::memory_order_acquire)))
        ;
    assert(*p2 == "Hello"); // never fires
    assert(data == 42); // never fires
}

int main()
{
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join(); t2.join();
}

However, I wonder why in the consumer thread data can not be a stale data. Is it because of the acquire operation?

1 Answers

Assignment to data happens-before ptr.store call. Accessing data happens-after that call (yes, by way of synchronization with the atomic object). Therefore, the access is guaranteed to see the value previously assigned.

Related