为什么ATOMIC_FLAG_INIT为假?

Mat*_*son 1 c++ atomic c++11

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

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
Run Code Online (Sandbox Code Playgroud)

ATOMIC_FLAG_INIT组的标志false,这意味着该线程永远不会在循环。一个(不好的)解决方案可能是这样做的:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Som*_*ude 5

您始终可以test_and_set在启动线程之前进行调用。

  • 因为它是构建其他原语的低级原语,而不是用于一般用途。“ atomic <bool>”是金钱所在。 (6认同)
  • 我已经在代码中做到了这一点,但是感觉很奇怪,并且吸引了您。我只是想知道为什么在初始化时无法将“ atomic_flag”设置为“ true”? (2认同)