lundi 31 décembre 2018

how to use c++ atomics

I'm confused about C++ atomic variables. If I have an atomic x that I want to increment in one thread and read in another thread, can I do ++x or do I have to do x.atomic_fetch_add(1). In the reader thread, can I do something like cout << x; or do I have to do cout << x.load().

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;
}

Is it guaranteed that thread two will see the value of (non atomic) x as 23. If not, if I change the access to y to use load and store, will that make a difference? Is it guaranteed that thread two will see the result of all non atomic operations that come before thread one sets y to true?

Can anyone suggest a book that explains these details clearly.

Aucun commentaire:

Enregistrer un commentaire