我有一个多线程应用程序,它必须经常读取一些数据,并且偶尔会更新这些数据。现在,互斥锁可以安全地访问该数据,但它很昂贵,因为我希望多个线程能够同时读取,并且仅在需要更新时将它们锁定(更新线程可以等待其他线程完成) .
我认为这是 boost::shared_mutex
应该做的,但我不清楚如何使用它,也没有找到一个明确的例子。
有没有人有一个简单的例子可以用来入门?
最佳答案
1800 INFORMATION 或多或少是正确的,但我想更正一些问题。
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,即使它没有升级(当我遇到它时我觉得这很尴尬)。所以,如果你所有的读者都是有条件的作家,你需要找到另一个解决方案。
关于c++ - boost shared_mutex(多次读取/一次写入)的示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/989795/