C++ atomic_flag query state

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

You cannot read the value of a std::atomic_flag without setting it to true. This is by design. It is not a boolean variable (we have std::atomic<bool> for that), but a minimal flag that is guaranteed lock free on all architectures that support C++11.

On some platforms the only atomic instructions are exchange instructions. On such platforms, std::atomic_flag::test_and_set() can be implemented with exchange var,1 and clear() with exchange var,0, but there is no atomic instruction for reading the value.

So, if you want to read the value without changing it, then you need std::atomic<bool>.


With C++20 we got the test() method, which does exactly what OP wants.