Concurrency: Understanding Atomic and Volatile in C 11 Memory Model
Consider a global variable accessed by multiple threads running concurrently on different cores. Each thread can both write to and read from the variable. Can one thread read outdated information from an atomic variable?
Volatile and Atomic: A Distinction
While atomic implies atomic access, volatile alone does not. Volatile finds use in situations like memory-mapped I/O and signal handling. It becomes redundant when paired with std::atomic. Furthermore, it bears no relevance to atomic access or inter-thread memory order.
Memory Ordering with Atomic Variables
The std::atomic library in C 11 offers an atomic integer type,
std::atomic<int> ai;
Read-Modify-Write (RMW) Operations: Guaranteeing Freshness
RMW operations, like exchange(), compare_exchange_strong(), and fetch_add(), offer a guarantee: they always act on the most recent value. In a series of calls to ai.fetch_add(1) from multiple threads, no duplicate or missing numbers will be returned. However, the threads may see the values at different points in time.
Caution and Conclusion
Understanding atomic operations is crucial. Thorough research and code review are recommended before using them in production code. Locks often provide a more accessible and nearly as efficient approach for concurrency.
The above is the detailed content of Can One Thread Read Stale Data from a C 11 Atomic Variable?. For more information, please follow other related articles on the PHP Chinese website!