简体   繁体   English

具有多个线程和互斥锁的竞争状况

[英]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 1)线程1执行步骤1并进入睡眠状态

2) Meanwhile Thread2 executes step-2 and changes value of iGlobe 2)同时,Thread2执行步骤2并更改iGlobe的值

How to overcome this situation? 如何克服这种情况?

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) . 因此,要修复您的代码,请将thread2Func更改为Lock(&Mutex1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM