28

Class atomic contains atomic versions of many different variable types. However, it doesn't contain an atomic enum type. Is there a way to use atomic enums or make my own? As far as I can tell, my only option is to either not use enums or use mutexes/semaphores to protect them.

Note: This bug report I found mentions "std::atomic enum support", but I don't see any mention of an atomic enum type in the C++ Standard, so I'm not sure what that refers to.

Cerran
  • 2,087
  • 2
  • 21
  • 33

2 Answers2

47

You can create an atomic enum like this:

#include <atomic>

enum Decision {stay,flee,dance};
std::atomic<Decision> emma_choice {stay}; // emma_choice is atomic

You can also do the same thing with enum classes:

#include <atomic>

enum class Decision {stay,flee,dance};
std::atomic<Decision> emma_choice {Decision::stay}; // emma_choice is atomic
Cerran
  • 2,087
  • 2
  • 21
  • 33
  • 1
    Interesting as I had the equivalent of `emma_choice = Decision::stay` and it would fail. Changing it with `emma_choice { Decision::stay }` made it compile. – Alexis Wilke Jan 14 '18 at 04:41
  • 1
    @AlexisWilke That's because the copy assignment operator is `delete`d for atomic types. If you did something like `emma_choice = Decision::stay`, then `Decision::stay` would first be implicitly converted to a `std::atomic`, and then copied over, but that's not allowed for atomics. So, you have to explicitly call a constructor to initialize an atomic. – Pacopenguin Dec 06 '22 at 19:49
  • @Pacopenguin I believe this is no longer the case in C++17 due to mandatory copy elision https://en.cppreference.com/w/cpp/language/copy_elision. Clang accepts it. – Ryan McCampbell Jun 23 '23 at 02:04
29

The generic atomic template can be used for all trivially copyable types, including enumerations. Whether or not it's lock-free is up to the implementation; hopefully it will be, if the underlying integer type is.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 18
    ... and one can check so with [is_lock_free()](http://en.cppreference.com/w/cpp/atomic/atomic/is_lock_free) – stefan Feb 13 '14 at 17:58