C ++ atomic_flag查询状态 [英] C++ atomic_flag query state
问题描述
我使用C ++ std :: atomic_flag
作为原子布尔标志。将标志设置为true或false不是一个问题,但是如何查询标志的当前状态,而不将其设置为某个值?我知道有方法' atomic_flag_clear
'和' atomic_flag_set
'。它们返回先前状态,但也修改当前状态。有没有办法查询标志状态而不修改它,或者我必须使用完全成熟的' std :: atomic< bool>
'。
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>
'.
推荐答案
无法读取 std :: atomic_flag
的值将其设置为 true
。这是设计。它不是一个布尔变量(我们有 std :: atomic< bool>
),但是一个最小标志被保证在支持C ++ 11。
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.
在某些平台上,唯一的原子指令是交换指令。在这些平台上, std :: atomic_flag :: test_and_set()
可以用 exchange var,1
和 clear()
与交换var,0
,但没有读取该值的原子指令。
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.
因此,如果你想读取值而不改变它,那么你需要 std :: atomic< bool>
。
So, if you want to read the value without changing it, then you need std::atomic<bool>
.
这篇关于C ++ atomic_flag查询状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!