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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3