Std::atomic_flag lock-free issue


I am not sure if I understand it. The documentation of std::atomic_flag says “it is guaranteed to be lock-free”.
So let’s say I have flag declared like that (in my mainThreadClass):

std::atomic_flag myFlag;
myFlag.test_and_set(); // to be sure initialized value is true

So what would happen if in my mainThreadClass I call myFlag.clear() (and it’s called only once during whole program) and unfortunately exactly at the same time in other thread I call:

    ... do something ...

To be more precise: What happen if myFlag.clear() occurs between test and set. AND - which is important - what is first in test_and_set, testing first and then setting, or vice versa?

I am asking because let’s imagine that:
First is testing, and the initialised value was true so it returns true, and then flag is set to false by myFlag.clear() (I remind it happen only once), and then is setting, which means flag is again true, so next iteration of while loop will get true from test_and_set, and due to fact myFlag.clear() will be no more called, my while is endless.

How to be sure to avoid that?


I think it might be a good idea to read up or research atomics a bit more. They’re not exactly intuitive…

This is a good talk to start with:

Fedor Pikus also has some good talks on atomics.