Home > Article > Backend Development > Why Use `memory_order_seq_cst` to Set a Stop Flag If You Check It with `memory_order_relaxed`?
In his "atomic<> weapons" talk, Herb Sutter demonstrates an example where a main thread sets a stop flag using memory_order_seq_cst and multiple worker threads check the flag using memory_order_relaxed. Sutter explains that using memory_order_relaxed for checking is acceptable due to the negligible latency impact. However, he suggests using memory_order_seq_cst for the operation that sets the flag, without providing a specific reason.
Understanding the concept of memory ordering is crucial here. Memory orders define the visibility and synchronization guarantees provided by atomic operations. In this example, the use of memory_order_seq_cst for setting the flag ensures the following:
While using memory_order_seq_cst for the write operation may seem excessive given that the load operation uses memory_order_relaxed, it actually has no significant performance implications. Implementations are required to make atomic stores visible within a reasonable amount of time, regardless of the memory order used.
While the latency impact of using memory_order_seq_cst for the write operation is minimal, it provides several benefits:
In conclusion, using memory_order_seq_cst for setting the stop flag in this example is not for performance optimization but to ensure correctness and thread safety. While memory_order_relaxed is acceptable for the load operation, using memory_order_seq_cst for the write operation provides additional guarantees without compromising performance.
The above is the detailed content of Why Use `memory_order_seq_cst` to Set a Stop Flag If You Check It with `memory_order_relaxed`?. For more information, please follow other related articles on the PHP Chinese website!