Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Multithread with global variables

Anyone know whether primitive global variable is thread safe or not?

// global variable
int count = 0;

void thread1()
{
   count++;
}

void thread2()
{
   count--;
   if (count == 0) print("Stuff thing");
}

Can I do it this way without any lock protection for count?

Thank you.

like image 761
longbkit Avatar asked Jun 23 '11 07:06

longbkit


2 Answers

This is not threadsafe. You have a race-condition here. The reason for that is, that count++ is not necessarily atomic (means not a single processor operation). The value is first loaded, then incremented, and then written back. Between each of these steps, the other thread can also modify the value.

like image 152
Björn Pollex Avatar answered Sep 25 '22 22:09

Björn Pollex


No, it's not. It may be, depending on the implementation, the compile-time options and even the phase of the moon.

But the standard doesn't mandate something is thread-safe, specifically because there's nothing about threading in the current standard.

See also here for a more detailed analysis of this sort of issue.

If you're using an environment where threads are supported, you can use a mutex: examine the pthread_mutex_* calls under POSIX threads, for example.

If you're coding for C++0x/C++11, use either a mutex or one of the atomic operations detailed in that standard.

like image 43
paxdiablo Avatar answered Sep 22 '22 22:09

paxdiablo