I am confused of speed different between using the mutex lock() and unlock() inside and outside a for loop. I got a global variable value and a function that increments it 1000000 times. This function is run in parallel by 5 threads. I measured the time elapsed and got these results:
mutex.lock();
for(int i = 0; i < 1000000; i++)
{
value++;
}
mutex.unlock();
0.160921 seconds
and:
for(int i = 0; i < 1000000; i++)
{
mutex.lock();
value++;
mutex.unlock();
}
2.10521 seconds
I assume with the second inner mutex arrangement the control is too fine and a lot of time is spent between the threads switching? or is there something else?