为什么ATOMIC_FLAG_INIT为假? [英] Why is ATOMIC_FLAG_INIT false?

查看:92
本文介绍了为什么ATOMIC_FLAG_INIT为假?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++11中,有一个std::atomic_flag对于线程循环很有用:

In C++11 there is the std::atomic_flag that is useful for thread loops:

static std::atomic_flag s_done(ATOMIC_FLAG_INIT);

void ThreadMain() {
    while (s_done.test_and_set()) {  // returns current value of s_done and sets to true
        // do some stuff in a thread
    }
}

// Later:
  s_done.clear();  // Sets s_done to false so the thread loop will drop out

ATOMIC_FLAG_INIT将标志设置为false,这意味着线程永远不会进入循环.一个(不好的)解决方案可能是这样做的:

The ATOMIC_FLAG_INIT sets the flag to false which means that the thread never gets in the loop. A (bad) solution is possibly to do this:

void ThreadMain() {
    // Sets the flag to true but erases a possible false
    // which is bad as we may get into a deadlock
    s_done.test_and_set();
    while (s_done.test_and_set()) {
        // do some stuff in a thread
    }
}

std::atomic_flag的默认构造函数指定该标志将处于未指定状态.

The default constructor for std::atomic_flag specifies that the flag will be in an unspecified state.

我可以将atomic_flag初始化为true吗?这是atomic_flag的正确用法吗?

Can I initialize the atomic_flag to true? Is this the correct use of the atomic_flag?

推荐答案

您始终可以在启动线程之前调用test_and_set.

You could always call test_and_set before starting the thread.

这篇关于为什么ATOMIC_FLAG_INIT为假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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