c++ - 我必须对 "exit"bool 变量使用 atomic<bool> 吗?

标签 c++ c++11 atomic

我需要设置一个标志让另一个线程退出。那个其他线程不时检查退出标志。我是否必须对标志使用 atomic 或仅使用纯 bool 就足够了,为什么(举例说明如果我使用纯 bool 可能会出现什么问题)?

#include <future>
bool exit = false;
void thread_fn()
{
    while(!exit)
    {
        //do stuff
        if(exit) break;
        //do stuff
    }
}
int main()
{
    auto f = std::async(std::launch::async, thread_fn);
    //do stuff
    exit = true;
    f.get();
}

最佳答案

Do I have to use atomic for “exit” bool variable?

是的

使用atomic<bool> ,或通过(例如)std::mutex 使用手动同步.您的程序当前包含一个数据竞争,一个线程可能读取一个变量,而另一个线程正在写入它。这是未定义的行为。

根据 C++11 标准的第 1.10/21 段:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.

冲突”的定义见第 1.10/4 段:

Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

关于c++ - 我必须对 "exit"bool 变量使用 atomic<bool> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16111663/

相关文章:

c++ - 推断大多数模板对象的参数,但在调用模板函数时与其他对象一起显式?

具有移尾功能的无锁队列算法

linux - 为什么不能在 32 位系统上原子访问 64 位值?

c++ - "-nan"是什么意思,是什么原因造成的?

c++ - 如何计算 OpenCV 中矩阵的直方图?

c++ - 变体类型和可变参数模板的转换和输出运算符

c++ - 可变参数模板未在 MSVC 中编译?

c++ - 我在 C++11 中使用 atomic_compare_exchange_strong 还是 atomic_exchange?

c++ - 如何通过 .props 文件设置调试符号路径

c++ - 有选择地仅对翻译单元的一部分禁用 GCC 警告