Home >Backend Development >C++ >Why Don't Compilers Merge Redundant Atomic Writes of the Same Value?
Why Compilers Avoid Merging Redundant Atomic Writes
Introduction
Compilers often adhere to the "as-if" rule, allowing them to reorder operations as long as the observable behavior remains consistent. However, in the case of consecutive stores to an atomic variable with the same value, such as:
std::atomic<int> y(0); void f() { auto order = std::memory_order_relaxed; y.store(1, order); y.store(1, order); y.store(1, order); }
compilers tend to issue the writes separately.
Limitations of the C Standard
While the C 11 and C 14 standards technically allow for the three stores to be merged, they do not guarantee that an observer will ever see the intermediate value of 2. Thus, optimizing by folding the stores into a single operation would violate the standard's intention of allowing any valid ordering.
Compiler Considerations
Compilers prioritize optimizing performance over predictability, which leads to conservative approaches. Despite the permissiveness of the standard, compilers opt not to merge atomic writes to avoid potential issues, such as progress bars that become stuck when multiple stores are incorrectly coalesced.
Principle of Least Surprise
Programmers typically expect atomic stores to occur sequentially, with each store being executed as written. If a compiler were to merge these operations, it could introduce unexpected behavior and violate the principle of least surprise.
Upcoming API Enhancements
Discussions are ongoing in C working groups to extend the std::atomic API with additional optimization controls. This would allow compilers to optimize atomic writes in cases where it is beneficial without violating the ordering requirements.
Alternative Solutions
In the meantime, programmers can use volatile atomic variables to prevent store optimizations. While this method mostly addresses the progress bar issue, it is not an ideal long-term solution.
Conclusion
Compilers typically do not merge consecutive atomic writes with the same value to ensure consistency with the C standard, avoid potential performance issues, and adhere to the principle of least surprise. However, future API enhancements may enable compilers to safely implement this optimization in the future.
The above is the detailed content of Why Don't Compilers Merge Redundant Atomic Writes of the Same Value?. For more information, please follow other related articles on the PHP Chinese website!