简体   繁体   English

C++ atomic_flag 查询状态

[英]C++ atomic_flag query state

I am using C++ std::atomic_flag as an atomic Boolean flag.我使用 C++ std::atomic_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?将标志设置为 true 或 false 不是问题,但是如何在不将其设置为某个值的情况下查询标志的当前状态? I know that there are methods ' atomic_flag_clear ' and ' atomic_flag_set '.我知道有方法“ atomic_flag_clear ”和“ 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<bool> '。

You cannot read the value of a std::atomic_flag without setting it to true .如果不将std::atomic_flag设置为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<bool> ),而是一个保证在所有支持 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.在这样的平台上, std::atomic_flag::test_and_set()可以通过exchange var,1clear()exchange var,0 ,但没有读取值的原子指令。

So, if you want to read the value without changing it, then you need std::atomic<bool> .因此,如果您想在不更改的情况下读取该值,则需要std::atomic<bool>

If you want to use atomic_flag to determine whether a thread should exit, you can do it like this:如果你想使用atomic_flag来判断一个线程是否应该退出,你可以这样做:

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

使用 C++20,我们得到了test()方法,它完全符合 OP 的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM