Home >Backend Development >C++ >Why Use `memory_order_seq_cst` for Setting a Stop Flag Checked with `memory_order_relaxed`?
Why Utilize memory_order_seq_cst for Setting Stop Flag if Checked with memory_order_relaxed?
In his "atomic<> weapons" presentation, Herb Sutter showcases atomic variable usage, including a scenario involving:
Workers checking a stop flag:
while (!stop.load(std::memory_order_relaxed)) { // Perform tasks }
Sutter asserts that using memory_order_relaxed for checking the flag is acceptable due to minimal impact on thread stopping delay. However, the reason for employing memory_order_seq_cst for setting the stop flag remains unclear.
Analysis:
mo_relaxed is Sufficient for Both Loading and Storing Stop Flag:
There is no significant latency benefit in utilizing stronger memory orders, even if the latency of observing changes in stop or keep_running flags is crucial.
It is unclear why Sutter advises against relaxed store operations. However, the ISO C standard does not specify store visibility timing or factors affecting it. Implementations are only mandated to ensure visibility within a finite period.
Inter-Thread Latency and Implementation:
Inter-thread latency is primarily determined by the implementation. Real-world C implementations leverage hardware cache coherence mechanisms, typically resulting in low latency (tens of nanoseconds) for store visibility.
Neither seq_cst nor relaxed memory orders hasten store visibility; they merely control the behavior of subsequent operations relative to the store or load. Stronger orders do not accelerate events but delay other operations until the specified order is maintained.
Relaxed Visibility and Hardware Cache Coherency:
On real hardware with cache coherency, memory orders do not enhance store visibility timing; they solely manage the ability of subsequent operations to become globally visible before store commitment.
Benefits of Relaxed Memory Order for Stop Flag:
The primary benefits of relaxed memory order for checking the stop flag are:
Conclusion:
In this scenario, memory_order_relaxed is appropriate for both loading and storing the stop flag. memory_order_seq_cst is not necessary for enhancing store visibility timing. Instead, it is used to enforce the desired ordering of subsequent operations and avoid issues with simultaneous writers.
The above is the detailed content of Why Use `memory_order_seq_cst` for Setting a Stop Flag Checked with `memory_order_relaxed`?. For more information, please follow other related articles on the PHP Chinese website!