Why Atomic Writes Are Not Optimized in Compilers
Question: Why don't compilers merge redundant atomic writes of the same value to a single atomic variable?
Explanation:
The C 11/14 standards allow for the folding or coalescing of consecutive stores to an atomic variable into a single store. In some cases, this optimization can be performed even when the stores have different values. However, compilers do not currently perform this optimization due to several factors.
Reasons for Optimization Avoidance:
Solutions and Future Considerations:
Currently, there is no way to explicitly control this optimization in the C 11/14 standards. However, discussions are underway to extend the std::atomic API to give programmers more control over such optimizations. This could enable compilers to perform optimizations when useful without violating ordering rules.
Alternative Approach:
Using volatile atomic variables can prevent compilers from optimizing away atomic stores. However, it is not a foolproof solution and may still lead to unexpected behavior in some cases.
The above is the detailed content of Why Don't Compilers Optimize Redundant Atomic Writes?. For more information, please follow other related articles on the PHP Chinese website!