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

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

问题描述

我需要为另一个线程退出设置一个标志.另一个线程会不时检查退出标志.我是否必须对标志使用atomic还是仅使用普通布尔变量就足够了,为什么?(并举例说明如果使用普通布尔变量可能会出问题)?

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();
}

推荐答案

我必须对出口"布尔变量使用原子吗?

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

.

要么使用atomic<bool>,要么通过(例如)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:

两个表达式评估 conflict (如果其中之一修改了内存位置(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天全站免登陆