In a scenario where a global variable is concurrently accessed by multiple threads on different cores, it is crucial to consider the implications of using atomic and volatile variables.
Volatile Keyword
The volatile keyword ensures that the compiler does not optimize memory operations for the variable, causing the processor to always read the value directly from memory. However, while volatile guarantees direct memory access, it does not imply atomic access.
Atomic Data Types
Standard C 11 includes atomic data types denoted as . These types provide atomic operations, meaning that each operation is guaranteed to execute without interference from other threads. This ensures that the latest value is always read, regardless of cache inconsistencies.
In the absence of additional synchronization (such as locks), shared global variables exhibit visibility and ordering constraints determined by the memory ordering parameter used in operations. While the default ordering () establishes a single total order, stale values may still be observed.
However, read-modify-write operations (such as ) guarantee that the operation is always performed on the latest value. This ensures that consecutive read-modify-write operations on the same variable will return a sequence of unique and ordered values.
While volatile variables ensure direct memory access, they do not guarantee atomic operations. For reliable and concurrent access to shared variables, atomic data types () should be used in conjunction with appropriate synchronization primitives to ensure correct program behavior.
The above is the detailed content of C 11 Concurrency: When Should I Use Atomic vs. Volatile Variables?. For more information, please follow other related articles on the PHP Chinese website!