dimanche 4 octobre 2020

c++: atomic variable's value is invalid when saved in local variable

I defined atomic variable current inside some Obj-C file:

std::atomic<long long> current;

after that it was initiated:

current=4;

After that the variable became accessible by number of threads. Some threads modified the variable like this:

current=(current.fetch_add(1))%4;

While other threads modified the variable in different way:

current.fetch_add(1);
if(current>=4){
    current=0;
}

Finally next line is executed:

long long cs=current;

At this point something strange happened: it appears in debugger that cs is 4 while current has different value, usually 1. My expectation was that cs should have the latest value of current and should never be greater than 3. I checked all other instances of current; they are not many and used properly everywhere. What am I missing?

Aucun commentaire:

Enregistrer un commentaire