C++ atomic_flag query state

前端 未结 2 1601
攒了一身酷
攒了一身酷 2021-01-01 09:19

I am using C++ std::atomic_flag as an atomic Boolean flag. Setting the flag to true or false is not a problem but how to query the current state of flag without

2条回答
  •  [愿得一人]
    2021-01-01 09:56

    If you want to use atomic_flag to determine whether a thread should exit, you can do it like this:

    Initialization:

    std::atomic_flag keep_running = ATOMIC_FLAG_INIT;
    keep_running.test_and_set();
    

    Thread loop:

    while (keep_running.test_and_set()) {
        // do thread stuff
    }
    

    When you want the thread to exit:

    keep_running.clear();
    

提交回复
热议问题