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
?
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):
g_maxValue
to a registerg_maxValue