Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an atomic enum in C++?

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.

like image 817
Cerran Avatar asked Feb 13 '14 14:02

Cerran


People also ask

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

What is enum example?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

What is the size of enum in C?

The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.


2 Answers

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 
like image 128
Cerran Avatar answered Oct 10 '22 16:10

Cerran


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.

like image 37
Mike Seymour Avatar answered Oct 10 '22 16:10

Mike Seymour