Home >Backend Development >C++ >Is `volatile` Still Relevant in C 11\'s Multi-Threaded World?
Volatile in C 11: Deprecation or Adaptation?
In the C 11 standard, the shift from a single-threaded to a multi-threaded machine model raises the question: Will the common example of optimized-out read in C 98/03, still be an issue in C 11?
Single-Threaded vs. Multi-Threaded Considerations
The C 98/03 memory model assumed a single-threaded environment, ignoring the possibility of concurrent access to variables. Hence, compilers could optimize away reads from variables labeled as "static int x;," as seen in the example code.
However, C 11 introduces a multi-threaded memory model, acknowledging the potential for concurrent variable access. This model, however, does not explicitly consider or prevent the optimized-out read behavior.
Volatile: Defining Scope
Volatile is a keyword added in C 98 to address hardware memory access optimizations. It instructs the compiler that a variable can change externally and should not be optimized away.
In the context of C 11's multi-threaded model, volatile does not directly influence threading behavior. It solely ensures that memory reads from the variable are not optimized away. However, this does not guarantee visible changes from another thread.
Memory Integrity and Atomicity
C 11's memory model focuses on memory integrity rather than threading behavior. Non-atomic access to variables (excluding std::atomics and mutexes) results in undefined behavior. Even with volatile, undefined behavior still occurs if another thread modifies the variable without proper synchronization.
Synchronization and Memory Barriers
For multithreaded communication, C 11 provides specific language constructs that invoke memory barriers. These barriers force data synchronization among different cores and ensure visibility of data writes across threads. Volatile does not provide this functionality.
Conclusion
In C 11, the optimized-out read issue persists for non-atomic accesses. Threading considerations remain crucial, and proper synchronization mechanisms using mutexes or std::atomics ensure defined behavior. While volatile may prevent memory read optimizations, it does not address threading issues or guarantee visible data changes across threads.
The above is the detailed content of Is `volatile` Still Relevant in C 11\'s Multi-Threaded World?. For more information, please follow other related articles on the PHP Chinese website!