In concurrencyInAction, it is stated as follows:
All operations on an atomic type are defined as atomic, and assignment and copy-construction involve two objects. A single operation on two distinct objects can't be atomic.
But I'm a little confused
atomic<int> i1, i2;
i1 = 0;
i2 = 1;
i1 = i2; // error
i1.store(i2); // but it works, is this operation atomic?
The last line of the code completes the assignment, it also involved two objects
atomic<int> i1, i2;
i1 = 0; // this is calling atomic<int>& atomic<int>::operator=(int)
i2 = 1; // this is also calling atomic<int>& atomic<int>::operator=(int)
i1 = i2; // this is also calling
// atomic<int>& atomic<int>::operator=(constatomic<int>&)
// (so called copy assignement operator which is explicitly deleted
// https://en.cppreference.com/w/cpp/atomic/atomic/operator%3D)
// this is completely different beast
i1.store(i2);
// it actually does two things:
int temporary = i2.load(); // *1
i2.store(temporary); // *2
// what happens here is:
// -> i2 get implicitly converted to int (*1)
// -> i1.store gets called with that int (*2)
// each of those 2 instructions are atomic but not both of them at once
// in other words they i1.store(i2) is not atomic as a whole
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.