Home > Blockchain >  Is the increment (operator ) thread-safe in C ?
Is the increment (operator ) thread-safe in C ?

Time:08-17

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?

CodePudding user response:

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

CodePudding user response:

No, it is not. The increment operation is internally computed as three different operations:

load operator

add 1

write operator

It is possible for one write operation to overwrite another if they are executed in parallel .

  • Related