我试图理解 boost shared_mutex 的源代码,但被困在unlock_shared()
方法中。
以下来自boost1.68的代码副本,第 241 ~ 264 行:
void unlock_shared()
{
boost::unique_lock<boost::mutex> lk(state_change);
state.assert_lock_shared();
state.unlock_shared();
if (state.no_shared())
{
if (state.upgrade)
{
// As there is a thread doing a unlock_upgrade_and_lock that is waiting for state.no_shared()
// avoid other threads to lock, lock_upgrade or lock_shared, so only this thread is notified.
state.upgrade=false;
state.exclusive=true;
//lk.unlock();
upgrade_cond.notify_one();
}
else
{
state.exclusive_waiting_blocked=false;
//lk.unlock();
}
release_waiters();
}
}
当最后一个 reader unlock_shared 时,如果有升级锁正在升级,它会设置state.upgrade
tofalse
和state.exclusive
totrue
然后 notify upgrade_cond
。
我知道设置state.exclusive
为true
可以避免其他线程到lock
,lock_upgrade
或lock_shared
。
但是为什么设置state.upgrade
为false
? 如果去掉这条线,会发生什么?