c++ - boost shared_mutex(多次读取/一次写入)的示例?

标签 c++ multithreading boost mutex boost-thread

我有一个多线程应用程序,它必须经常读取一些数据,并且偶尔会更新这些数据。现在,互斥锁可以安全地访问该数据,但它很昂贵,因为我希望多个线程能够同时读取,并且仅在需要更新时将它们锁定(更新线程可以等待其他线程完成) .

我认为这是 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/

相关文章:

c++ - 我应该并行化哪些循环,外部循环还是内部循环

c++ - 被连续迭代的线程安全无序映射

c - 在线程中使用时,recvfrom() 对于 RAW 套接字返回 -1?

c++ - 在 Win32/MFC 中停止线程

c++ - 控件单击以在 IDE 中获取定义不起作用

c++ - QObject::sender() 在插槽中无法正常工作

c++ - 适用于原始指针上的迭代器以及 unique_ptr 上的迭代器的模板化函数

c++ - 用消息 boost static_assert?

c++ - 如何使用 boost lexical_cast 将字符串转换为 unsigned short?

c++ - 有序元素的最佳容器