在《并发行动》中指出:
原子类型上的所有操作都定义为原子的,并且赋值 复制构造涉及两个对象。一次操作对两个 不同的对象不能是原子的。
但是我有点困惑
atomic<int> i1, i2;
i1 = 0;
i2 = 1;
i1 = i2; // error
i1.store(i2); // but it works, is this operation atomic?
最后一行代码完成了赋值,还涉及到两个对象
atomic<int> i1, i2;
i1 = 0; // this is calling int atomic<int>::operator=(int)
i2 = 1; // this is also calling int atomic<int>::operator=(int)
i1 = i2; // this is also calling
// atomic<int>& atomic<int>::operator=(constatomic<int>&)
// (so called copy assignment 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