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

Mat*_*att 2 c++ boost

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

虽然我的其他问题的答案是有帮助的, 如何使用boost可升级互斥锁的示例

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

有人可以指点我或提供一个具体的例子,以这种方式使用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
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 8

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

例如

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.
}
Run Code Online (Sandbox Code Playgroud)

编辑:我还通过实验发现,如果你没有升级锁,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().
Run Code Online (Sandbox Code Playgroud)

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