Home >Backend Development >C++ >Why set the stop flag using memory_order_seq_cst, if you check it with memory_order_relaxed?
In video, Herb Sutter, discusses the use of atomics, including an example where a main thread launches worker threads. The workers check a stop flag, and the main thread eventually sets the stop flag to true using memory_order_seq_cst. Sutter explains that checking the flag with memory_order_relaxed is acceptable because the delay in stopping a thread is not significant.
The question arises as to why the stop flag is set with memory_order_seq_cst instead of memory_order_relaxed.
There is no meaningful latency benefit to stronger memory orders in this scenario, even if the latency of seeing a change to a stop or keep_running flag was important.
The ISO C standard does not specify how quickly stores become visible or what might influence that. It only requires that implementations ensure that the last value assigned by an atomic or synchronization operation becomes visible to all other threads within a finite period of time.
Inter-thread latency is primarily a quality-of-implementation issue, with the standard leaving things wide open. Normal C implementations typically compile to asm for some architecture and expose the hardware's cache-coherence properties, resulting in low inter-thread latency.
On real hardware that uses cache coherency, different memory orders for store or load do not make stores visible sooner in real time. They control whether later operations can become globally visible while waiting for the store to commit from the store buffer to L1d cache.
Stronger orders, and barriers, do not make things happen sooner in an absolute sense. They delay other things until they are allowed to happen relative to the store or load.
Using memory_order_relaxed for the load has the following performance benefits:
In this specific scenario, where the stop flag is set infrequently, the wasted work due to false loads is minimal. Therefore, the performance benefits of using memory_order_relaxed outweigh the potential drawbacks.
The above is the detailed content of Why set the stop flag using memory_order_seq_cst, if you check it with memory_order_relaxed?. For more information, please follow other related articles on the PHP Chinese website!