问题描述
我想检查 c>到 true 可以重新排序。
The commenter is right: a simple bool is insufficient, because non-atomic writes from the thread that sets thread_finished to true can be re-ordered.
一个静态变量 x 到一些非常重要的数字,然后发出其退出信号,如下所示:
Consider a thread that sets a static variable x to some very important number, and then signals its exit, like this:
x = 42; thread_finished = true;
当你的主线程看到 thread_finished true ,它假定工作线程已经完成。但是,当你的主线程检查 x 时,它可能会发现它设置了错误的数字,因为上面的两个写已重新排序。
When your main thread sees thread_finished set to true, it assumes that the worker thread has finished. However, when your main thread examines x, it may find it set to a wrong number, because the two writes above have been re-ordered.
当然这只是一个简单的例子来说明一般的问题。使用 std :: atomic 为您的 thread_finished 变量添加一个内存屏障所有写入完成之前。
Of course this is only a simplified example to illustrate the general problem. Using std::atomic for your thread_finished variable adds a memory barrier, making sure that all writes before it are done. This fixes the potential problem of out-of-order writes.
另一个问题是,对非易失性变量的读取可以优化出来,所以主线程永远不会注意到 thread_finished 标志的变化。
重要说明:使 thread_finished 强>去解决这个问题;事实上,volatile不应该与线程结合使用 - 它用于处理内存映射硬件。
Another issue is that reads to non-volatile variables can be optimized out, so the main thread would never notice the change in the thread_finished flag.
Important note: making your thread_finished volatile is not going to fix the problem; in fact, volatile should not be used in conjunction with threading - it is intended for working with memory-mapped hardware.
这篇关于是否有必要使用std :: atomic来表示线程已完成执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!