首页 > 解决方案 > 为什么 boost shared_mutex unlock_shared 需要在最后一个阅读器中将 state.upgrade 设置为 false?

问题描述

我试图理解 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.upgradetofalsestate.exclusivetotrue然后 notify upgrade_cond

我知道设置state.exclusivetrue可以避免其他线程到locklock_upgradelock_shared

但是为什么设置state.upgradefalse? 如果去掉这条线,会发生什么?

标签: c++boostconcurrencyreaderwriterlock

解决方案


推荐阅读