? " />
What is Atomic Object in std::atomic<>?
The std::atomic<> template provides a type that can be concurrently operated on by multiple threads without raising undefined behavior.
Atomicity of std::atomic<>
Each instantiation of std::atomic<> represents an atomic type that allows for simultaneous operations by different threads on its instances. Unlike regular C objects, atomic objects ensure exclusive access to their data, preventing data races.
Atomic Operations
Operations performed on atomic objects are atomic in nature. This means that:
Memory Order and std::atomic<>
std::atomic<> provides precise control over synchronization and memory order. It supports various memory order options, including:
Example: Arithmetic Operations
While individual arithmetic operators like = and are atomic operations, decomposing them into separate load, add, and store operations may not be atomic. For example:
a = a + 12;
This operation will involve the following steps:
Steps 2 and 3 are not atomic, so there is a potential race condition where another thread could modify a between the add and the store.
Alternatives to Basic Arithmetic Operations
For typical use cases involving arithmetic operations, it's recommended to use the equivalent overloaded operators defined in std::atomic<>. These operators perform the entire operation atomically, ensuring sequential consistency.
Additional Resources on Atomicity and Memory Model
The above is the detailed content of What is an Atomic Object in std::atomic<>?. For more information, please follow other related articles on the PHP Chinese website!