Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum and maximum possible value of a shared variable when incremented by multiple threads

I have a global shared variable and that is being updated 5 times by each of the 5 threads spawned. As per my understanding the increment operation is consisting of 3 instructions

load  reg, M
inc reg
store reg, M

So I want to ask that in this scenario what would be the maximum and minimum value given arbitrary interleaving in the 5 threads.

So according to me the maximum value will be 25 ( I am 100% sure that it can be more than 25) and the minimum value is 5. But I am not so sure on minimum value. Can it be less that 5 in some arbitrary interleaving ? Any inputs will be greatly appreciated.

/* Global Variable */
int var = 0;

/* Thread  function */
void thread_func()
{
     for(int c = 0; c < 5; c++)
             var++;
}
like image 493
Ketan Dixit Avatar asked Nov 21 '10 03:11

Ketan Dixit


1 Answers

Given your definition of increment, I agree with your max of 25.

However, I believe the min can be 2 under the following scenario. I've named the 5 threads A, B, C, D and E.

  1. A loads 0
  2. C, D, E run to completion
  3. B runs through 4 of its 5 iterations.
  4. A increments 0 to 1 and stores the result (1).
  5. B loads 1
  6. A runs to completion
  7. B increments 1 to 2 and stores 2.
like image 175
jtdubs Avatar answered Sep 23 '22 18:09

jtdubs