Volatile in C 11
The C 11 standard introduced a multi-threaded machine model, leading to questions about its impact on variable optimization. Specifically, the classic example of optimized-out reads from static variables (e.g., static int x; void func() { x = 0; while (x == 0) {} }) is brought into question.
Does the Multi-Threaded Model Eliminate Optimization Issues?
Contrary to expectations, the C 11 memory model does not guarantee the solution to this problem. While the multi-threaded model recognizes the possibility of variable changes, it does not assume atomic operations or consider threading behavior.
The Role of Volatile
Volatile does not address threading behavior; rather, it prevents memory read optimization. However, this does not ensure multi-threaded correctness. CPU caches and memory access synchronization require memory barriers, which volatile does not provide.
Undefined Behavior in Multi-Threaded Access
Without proper synchronization mechanisms (e.g., mutexes, atomic variables), non-atomic memory access (such as in the example code) yields undefined behavior in C 11. Both threads must cooperate to ensure memory integrity.
Synchronization and Memory Integrity
The C 11 memory model defines specific operations that trigger visibility of writes in one thread to other threads. Synchronization through locking or ordering ensures memory integrity.
Example Analysis
In the provided example, there is no synchronization or dependency ordering, leading to a data race and undefined behavior.
Conclusion
The multi-threaded model in C 11 does not eliminate the need for atomic operations or synchronization for multi-threaded correctness. Volatile alone does not guarantee multi-threaded safety; it merely prevents memory read optimization. Proper use of synchronization mechanisms remains essential for reliable multi-threaded applications.
The above is the detailed content of Does C 11\'s Multi-Threaded Model Solve Optimization Issues with Volatile Variables?. For more information, please follow other related articles on the PHP Chinese website!