Описание тега stdatomic
std::atomic
is a class template in the C++11 Standard Library, defined in the <atomic>
header. An atomic object of type std::atomic<X>
provides member functions to perform atomic operations on its member of type X
.
Like mutexes, atomic objects can be used for synchronization in multi-threaded C++ programs. Unlike mutexes or other locks, atomics can be used to build lock-free algorithms that allow concurrent readers and writers.
Atomics can even be used to build custom locking primitives (but that's usually a bad idea on systems with OS-supported locking functions that yield the CPU on contention).
Resources:
An Introduction to Lock-Free Programming, by Jeff Preshing, and other articles linked from it.
- Memory Reordering Caught in the Act: an experimental test of memory reordering on x86, and how
memory_order_seq_cst
avoids it. - Acquire and Release Semantics
- Memory Barriers Are Like Source Control Operations: LoadStore vs. StoreLoad vs. StoreStore vs. LoadLoad reordering explained.
Can num++ be atomic for 'int num'?: No, not on a multi-core machine, even if it compiles to a single assembly instruction (which isn't guaranteed). Discusses the difference between C++ and asm, and how atomicity works internally on a CPU.
Also points out that a compiler can merge
num++; num++;
into a singlenum+=2
, if allowed by the as-if rules. See http://wg21.link/p0062 and http://wg21.link/n4455.