在boost中使用作用域try_shared_lock和升级锁的示例

时间:2010-10-18 22:04:37

标签: c++ boost

我有一个使用来自boost库的共享互斥锁的线程池。

虽然我的其他问题的答案很有帮助, Example of how to use boost upgradeable mutexes

我已经意识到我实际需要的是不能阻止无法获得共享锁或升级锁。不幸的是,增强文档缺少使用中的任何示例。

有人可以指点我或提供一个具体说明以这种方式使用的shared_lock的例子。

boost:shared_mutex mutex;

void thread()
{
    // try to obtain a scoped shared lock
    // How do I do that?
}

void thread2()
{
   // try to obtain a scoped upgrade lock 
   // and then a scoped unique lock
}

1 个答案:

答案 0 :(得分:8)

答案似乎是你可以提供boost:try_to_lock作为其中几个范围锁的参数。

e.g。

boost::shared_mutex mutex;

// The reader version
boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock);
if (lock){
  // We have obtained a shared lock
}

// Writer version
boost::upgrade_lock<boost::shared_mutex> write_lock(mutex, boost::try_to_lock);
if (write_lock){
  boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
  // exclusive access now obtained.
}

编辑: 我还通过实验发现,如果您没有升级锁,upgrade_to_unique_lock将失败。你也可以这样做:

boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
if (unique_lock){
  // we are the only thread in here... safe to do stuff to our shared resource
}

// If you need to downgrade then you can also call
unique_lock.release();

// And if you want to release the upgrade lock as well (since only one thread can have upgraded status at a time)
write_lock.unlock().

注意:您必须先调用release然后解锁,否则您将获得锁定异常。 你当然可以让unique_lock和write_lock超出范围从而释放锁,虽然我发现有时候你想要早点发布它,你应该花很少的时间在那个状态。