Xin_Wang
Xin_Wang

Reputation: 1

performance differences between shared_mutex.lock and shared_mutex.lock_shared?

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!

Upvotes: 0

Views: 70

Answers (0)

Related Questions