如何实施不等待以防止死锁

How do I implement no hold and wait to prevent a deadlock

我写了一个有意死锁的代码,它有 2 个锁,我使程序死锁的方式是这样的:

void ThreadAtWork1(){
  m1.lock();
  cout<<"Thread 1 has been called\n";
  m2.lock();
  m1.unlock();
  m2.unlock();
}

void ThreatAtWork2(){
  m2.lock();
  cout<<"Thread 2 has been called\n";
  m1.lock();
  m2.unlock();
  m1.unlock();

}

我如何实施一个没有 'hold and wait' 的解决方案来阻止程序死锁?我知道我可以重新订购锁,但这不会解决不等待解决方案。

我的主要功能:

int main(int argc, const char * argv[]) {

thread t1(ThreadAtWork1);
thread t2(ThreatAtWork2);

t1.join();
t2.join();

cout<<"\nMain exited...\n";

return 0;
}

谢谢。

我怀疑 "no hold and wait" 是一个通用原则,您可以在其中尝试避免在锁定互斥锁时进行阻塞调用。除非您非常小心,否则这样做很容易导致死锁。

如果您确实需要同时锁定两个互斥体,"no hold and wait" 不适合您。

通常您可以重新设计您的系统而不需要同时锁定两个互斥体。例如,有多个条件变量与同一个互斥锁关联是完全可以的。

我前段时间确实弄明白了,但忘了更新这个post。下面是我如何去做并得到 100 分的。

//for hold and wait, just don't allocate the resource if a thread asks for it. Just wait and execute the other one

//t1-> request W. requires W
//t2-> has W
//t1 checks if W is free. wait
//t2 executes. Releases W
//t1 executes

//basically, if all locks are free, execute, else not.