deepdive
deepdive

Reputation: 11022

Race condition with multiple threads and mutex locks

int iGlobe = 0;
...
void thread1Func()
{
  Lock(&Mutex1);
  if(iGlobe == 0)         //step-1
    someaction();
}
...
void thread2Func()
{
  Lock(&Mutex2);
  iGlobe = 5;             //step-2
}

Suppose,

1) Thread1 executes step-1 and goes to sleep

2) Meanwhile Thread2 executes step-2 and changes value of iGlobe

How to overcome this situation?

Upvotes: 1

Views: 724

Answers (1)

Drew Hall
Drew Hall

Reputation: 29065

All accesses to a given piece of data have to synchronize on the same mutex, otherwise there is no "mutual exclusion" effect. So, to fix your code, change thread2Func to say Lock(&Mutex1).

Upvotes: 5

Related Questions