0

The scenario is: I have two shared_mutex for two shared variable a b, to prevent deadlock, if thread A get mutex_a but cannot get mutex_b, thread B get shared_mutex_b but cannot get shared_mutex_a, in this case, should thread A abandon mutex_a or should thread B abandon shared_mutex_b? Is there any performance difference between the two choice?


std::shared_mutex mutex_a, mutex_b;
int a, b;

void foo(){
  mutex_a.lock();
  if(mutex_b.try_lock()){
    do sth();
    mutex_a.unlock();
    mutex_b.unlock();
  }else{
    mutex_a.unlock();        // choice 1
  }
}

void bar(){
  mutex_b.lock_shared();
  if(mutex_a.try_lock_shared()){
    do sth();
    mutex_b.unlock_shared();
    mutex_a.unlock_shared();
  }else{
    mutex_b.unlock_shared();   //choice 2
  }
}

I know acquiring the two lock with the same order can prevent deadlock,but that is not the point!

Xin_Wang
  • 1
  • 1
  • Both sections of code need the avoidance path as it's not predictable as to which lock is locked first. – Richard Critten May 02 '23 at 09:02
  • 1
    The question is meaningless. Neither of the threads knows whether it is A or B. Both threads should abandon their locks. "I know acquiring the two lock with the same order can prevent deadlock,but that is not the point!": it is *exactly* the point, and there is no other point. – user207421 May 02 '23 at 10:20
  • As @RichardCritten said, both sections need the avoidance path. Just think about, that a third function `void foobar()` with the same structure as `void foo()` is needed. If you are using your "choice 2" you have chance to run into a deadlock again. Same behaviour if it has the same structure as `void bar()` and you use your "choice 1". – Bananenkönig May 02 '23 at 12:18
  • Maybe the code is misleading, my intention is just to wonder `lock/unlock` vs `lock_shared/unlock_shared`, which one is more efficient? – Xin_Wang May 02 '23 at 12:40
  • Base on the efficiency difference, I wanna take different measures. e.g. if `try_lock_shared` failed, I will `unlock_shared` immediately, however if `try_lock` failed, I will retry once. – Xin_Wang May 02 '23 at 12:45
  • The efficiency difference is meaningless too. You're running multithreaded code here, and some of it has to be blocked while the other runs. Unless your critical sections are astoundingly short, the efficiency or otherwise of the semaphore implementation is insignificant. You are barking up several wrong trees here. – user207421 May 03 '23 at 01:26

0 Answers0