atomic variables and ordering

If I have

int x;
atomic<bool> y;
then in thread one

if (!y)
{
x = 23;
y = true;
}
and in thread two

if (y)
{
cout << x;
y = false;
}

I believe it guaranteed that thread two will see the value of (non atomic) x as 23.

Is it correct to say that the atomic write to y forces the compiler to generate a "memory barrier" instruction and it 1) prevents both the compiler and the hardware from moving memory assignments across the barrier 2) it forces a cache flush so that all threads see the updated data. Does it also force the cache to be updated from external memory which might have been changed by other threads? Is it correct that other caches can still be not up to date at this point but they will be updated if they do an atomic read?
I see no such guarantee.

This could happen:
1
2
3
4
5
6
7
int x; // NOT INITIALISED - BEGINS AS SOME RANDOM VALUE - could be 126478376
atomic<bool> y;  // NOT INITIALISED - COULD BEGIN AS TRUE

THREAD 2 RUNS:
if (y) // y is TRUE, SO GO INTO THE IF BLOCK
{
cout << x; // OUTPUT THE RANDOM VALUE OF x , 126478376 


Since x and y have static storage duration, they would be zero initialised.

The default memory order for atomic operations is sequentially consistent ordering (a single total order in which all threads observe all modifications in the same order).


> Is it correct that other caches can still be not up to date at this point
> but they will be updated if they do an atomic read?

If they do an atomic read (with the default memory order) of the same atomic variable.
Topic archived. No new replies allowed.