c++ - 为什么 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.upgrade
tofalse
和state.exclusive
totrue
然后 notify upgrade_cond
。
我知道设置state.exclusive
为true
可以避免其他线程到lock
,lock_upgrade
或lock_shared
。
但是为什么设置state.upgrade
为false
? 如果去掉这条线,会发生什么?
解决方案
推荐阅读
- android - 通过在活动上调用finish()关闭应用程序后启动时崩溃
- sql - 我可以将表 1 列与表 2 行连接吗?
- java - 每次调用带有对象引用作为值的枚举是否会创建一个对象?
- javascript - 使用 javascript 进行实时表单验证
- python - 如何检查某个字符串是否在列表中重复多次
- c++ - 编写包含变量值的多行字符串
- vba - 如何将 .bas vba 模块文件内容(变量)集成/链接到 vba 项目中?
- javascript - 在 FORM 的选择中使用图像的最佳实践
- javascript - 在ngOnInit中调用函数时的Angular5打字稿
- regex - 如何使用 tesseract-ocr 从字符串中获取特定字段数据,而无需从图像中获取字段标签