简体   繁体   中英

Should a boolean flag always be atomic?

Suppose there is a boolean flag ( keep_running ) which is controlled by the main thread. Another thread loops indefinitely until this flag becomes false.

int main() {
    bool keep_running(true);
    std::thread run( [](bool &keep_running)
    {
        while(keep_running)
        {
            // do work
        }
    }, std::ref(keep_running) );

    // do other work
    keep_running = false;
    run.join();
    return 0;
}

Should that flag be atomic?

std::atomic<bool> keep_running

I imagine, the worst which can happen to the non-atomic version would be that the flag gets set right at the time when the

while(keep_running)

is executed. In which case, the loop keeps running for one more (not strictly needed) iteration. But in my case, this would be acceptable.

Is there a possible scenario where the above code could be wrong?

EDIT:

I'm mostly interested in this for performance reasons (and for not having bugs). Thus, would the use of std::atomic for the flag in the loop negatively impact performance?

It is just C++11 standard which forbids (mark them as Undefined Behaviour ) concurrent accesses to non-atomic variable.

So you need to declare this variable atomic.

Note, that using keep_running.load(std::memory_order_relaxed) for read value and keep_running.store(true, std::memory_order_relaxed) for write value will eliminate any additional perfomance costs, so resulted code will be as faster as one without atomic.


I imagine, the worst which can happen to the non-atomic version would be that the flag gets set right at the time.

It can be happen that in your thread the variable will be stored into register and never be reloaded (so thread will never be stopped). Without atomic or other special type and modifiers compiler is allowed to do that, and it actually does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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