Search code examples
c++winapiatomicinterlocked

Difference between interlocked variable access (on boolean) and std::atomic_flag


I was wondering what the differences are between accessing a boolean value using Windows' interlockedXXX functions and using std::atomic_flag.

To my knowledge, both of them are lock-less and you can't set or read an atomic_flag directly. I wonder whether there are more differences.


Solution

  • std::atomic_flag serves basically as a primitive for building other synchronization primitives. In case one needs to set or read, it might make more sense to compare with std::atomic<bool>.

    However, there are some additional (conceptual) differences:

    • With interlockedXXX, you won't get portable code.

    • interlockedXXX is a function, while std::atomic_flag (as well as std::atomic) is a type. That's a significant difference, since, you can use interlockedXXX with any suitable memory location, such as an element of std::vector. On the contrary, you cannot make a vector of C++ atomic flags or atomic bools, since the corresponding types do not meet the vector value type requirements. 1

    You can see the latter difference in the code created by @RmMm, where flag is an ordinary variable. I also added a case with atomic<bool> and you may notice that all the three variants produce the very same assembly:

    https://godbolt.org/z/9xwRV6


    [1] This problem should be addressed by std::atomic_ref in C++20.