C++ atomic_flag query state

前端 未结 2 1574
攒了一身酷
攒了一身酷 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:57

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

提交回复
热议问题