boost shared_mutex 的示例(多次读取/一次写入)?
我有一个多线程应用程序,它必须经常读取一些数据,并且偶尔会更新这些数据.现在互斥锁可以安全地访问该数据,但它很昂贵,因为我希望多个线程能够同时读取,并且仅在需要更新时将它们锁定(更新线程可以等待其他线程完成).
I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wait for the other threads to finish).
我认为这是 boost::shared_mutex
应该做的,但我不清楚如何使用它,也没有找到一个明确的例子.
I think this is what boost::shared_mutex
is supposed to do, but I'm not clear on how to use it, and haven't found a clear example.
有没有人有一个简单的例子可以让我开始使用?
Does anyone have a simple example I could use to get started?
推荐答案
看起来你会这样做:
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// now we have exclusive access
}
相关文章