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 setting it to some value? I know that there are methods 'atomic_flag_clear
' and 'atomic_flag_set
'. They do give back the previous state but also modify the current state. Is there any way to query flag state without modifying it or do I have to use full fledged 'std::atomic<bool>
'.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Difference between Thread#run and Thread#wakeup?
- Selecting only the first few characters in a strin
- Java/Spring MVC: provide request context to child
- What exactly do pointers store? (C++)
You cannot read the value of a
std::atomic_flag
without setting it totrue
. This is by design. It is not a boolean variable (we havestd::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 withexchange var,1
andclear()
withexchange 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>
.If you want to use
atomic_flag
to determine whether a thread should exit, you can do it like this:Initialization:
Thread loop:
When you want the thread to exit: