C++ – thread synchronization – delicate issue


let's i have this loop :

static a;
for (static int i=0; i<10; i++)
   ///// point A

to this loop 2 threads enters…

i'm not sure about something…. what will happen in case thread1 gets into POINT A , stay there, while THREAD2 gets into the loop 10 times, but after the 10'th loop after incrementing i's value to 10, before checking i's value if it's less then 10,
Thread1 is getting out of the loop and suppose to increment i and get into the loop again.
what's the value that Thread1 will increment (which i will he see) ? will it be 10 or 0 ?

is it posibble that Thread1 will increment i to 1, and then thread 2 will get to the loop again for 9 times (and them maybe 8 ,7 , etc…)


Best Solution

You have to realize that an increment operation is effectively really:

read the value
add 1
write the value back

You have to ask yourself, what happens if two of these happen in two independent threads at the same time:

static int a = 0;

thread 1 reads a (0)
adds 1 (value is 1)
thread 2 reads a (0)
adds 1 (value is 1)
thread 1 writes (1)
thread 2 writes (1)

For two simultaneous increments, you can see that it is possible that one of them gets lost because both threads read the pre-incremented value.

The example you gave is complicated by the static loop index, which I didn't notice at first. Since this is c++ code, standard implementation is that the static variables are visible to all threads, thus there is only one loop counting variable for all threads. The sane thing to do would be to use a normal auto variable, because each thread would have its own, no locking required.

That means that while you will lose increments sometimes, you also may gain them because the loop itself may lose count and iterate extra times. All in all, a great example of what not to do.