Reputation: 1177
Is the +=
operator in c++ thread-safe?
It is possible to imagine a situation where it is not (Pseudocode):
int a = 5;
void thread1 () {
a += 5;
}
void thread2 () {
a += 5;
}
void main () {
start_thread1 ();
start_thread2 ();
//Prints 15 always, but i think 10 is not impossible.
printf ("%d\n", a);
}
It is obvious, that i must use Mutexes when += is overloaded, but do i have to set a mutex when working with simple types?
Upvotes: 1
Views: 1081
Reputation: 15524
It is not thread-safe.
To get synchronized behaviour without using blocking (mutexes) you could e.g. use the C++11 wrapper std::atomic
.
std::atomic<int> a{5};
void work() {
a += 5; // Performed atomically.
}
int main() {
std::thread t1{work};
std::thread t2{work};
t1.join();
t2.join();
std::cout << a << std::endl; // Will always output 15.
}
Upvotes: 7
Reputation: 385144
+=
is not atomic, so indeed it is not thread-safe and you could get 10
. Or, frankly, cows being ejected from the moon. Perhaps a pizza materialising around your dog's nose.
Upvotes: 8