c++ - 为什么 ATOMIC_FLAG_INIT 是假的?

标签 c++ c++11 atomic

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

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
    }
}

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

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

最佳答案

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

关于c++ - 为什么 ATOMIC_FLAG_INIT 是假的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17883703/

相关文章:

c++ - 实现自定义非线性最小化,从符号数学到 C

C++:调用 tuple_transpose 函数时没有匹配的函数调用

c++ - ld : symbol(s) not found for architecture x86_64 error

c++ - 如果没有 "usleep()"或 "printf",While 循环将不会终止

java - 用于线程安全的 volatile 关键字

c++ - 不要真正理解 std::atomic::compare_exchange_weak 和 compare_exchange_strong 的逻辑

c++ - 返回空指针

c++ - 如何通过按下按钮来格式化 QTextEdit 中的选定文本

c++ - 如何在与定义分离的 void 上实现部分专用模板?

c - 访问静态初始化变量时是否应该使用屏障?