我有一个多线程应用程序,必须经常读取一些数据,并且偶尔会更新数据。现在,互斥体可以安全地访问该数据,但它很昂贵,因为我希望多个线程能够同时读取,并且仅在需要更新时将它们锁定(更新线程可以等待其他线程完成) 。
我想这就是boost::shared_mutex
应该这样做,但我不清楚如何使用它,也没有找到明确的例子。
有人有一个我可以用来入门的简单示例吗?
1800 信息或多或少是正确的,但有一些问题我想纠正。
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
void unconditional_writer()
{
boost::unique_lock< boost::shared_mutex > lock(_access);
// do work here, with exclusive access
}
另请注意,与shared_lock不同,只有一个线程可以一次获取upgrade_lock,即使它没有升级(当我遇到它时,我认为这很尴尬)。所以,如果你所有的读者都是有条件的作家,你需要找到另一种解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)