4

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.

Ben
  • 1,519
  • 23
  • 39
  • 1
    https://godbolt.org/z/s8Qn4I – RbMm Sep 17 '19 at 10:33
  • 1
    No differences, it just took a very long time to get std::atomic added to the standard. The Interlocked functions existed 5 years before the 1st C++ standard was published. – Hans Passant Sep 17 '19 at 11:27

1 Answers1

4

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Daniel Langr
  • 22,196
  • 3
  • 50
  • 93