Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is the increment thread-safe in C++?

Is the following function thread-safe (in C++) or do I have to add a mutex?

int example() {
    return g_maxValue++;
}

where int g_maxValue is some global integer. If yes, does the same hold true
for all integer types such as uint64_t?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Thread safety is guaranteed only for atomic variables (std::atomic).

From C++ standard:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.

The compiler doesn’t have to consider thread safety for non-atomic variables, so it is allowed to translate ++ to multiple operations (pseudo code):

  1. Read g_maxValue to a register
  2. Increment the value in the register
  3. Store the value to g_maxValue
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading