我是否必须使用 atomic<bool>用于“退出"布尔变量? [英] Do I have to use atomic<bool> for "exit" bool variable?

查看:26
本文介绍了我是否必须使用 atomic<bool>用于“退出"布尔变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为另一个线程设置一个标志以退出.另一个线程不时检查退出标志.我必须对标志使用 atomic 还是只使用普通 bool 就足够了,为什么(举个例子,如果我使用普通 bool 可能会出错)?

I need to set a flag for another thread to exit. That other thread checks the exit flag from time to time. Do I have to use atomic for the flag or just a plain bool is enough and why (with an example of what exactly may go wrong if I use plain 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();
}

推荐答案

对于exit" bool 变量,我必须使用 atomic 吗?

Do I have to use atomic for "exit" bool variable?

是的.

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

Either use atomic<bool>, or use manual synchronization through (for instance) an std::mutex. Your program currently contains a data race, with one thread potentially reading a variable while another thread is writing it. This is Undefined Behavior.

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

Per Paragraph 1.10/21 of the C++11 Standard:

如果程序在不同线程中包含两个冲突动作,则该程序的执行包含数据竞争,至少其中一个不是原子的,并且都不在另一个之前发生.任何此类数据竞争都会导致未定义的行为.

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 段:

The definition of "conflicting" is given in Paragraph 1.10/4:

两个表达式评估冲突,如果其中一个修改了内存位置 (1.7) 而另一个访问或修改相同的内存位置.

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.

这篇关于我是否必须使用 atomic&lt;bool&gt;用于“退出"布尔变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆