Search code examples
c++thread-safetystdatomic

Is the increment (operator++) 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 std::uint64_t?


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