【问题标题】:Example of using scoped try_shared_lock and upgrade lock in boost在 boost 中使用作用域 try_shared_lock 和升级锁的示例
【发布时间】:2011-04-27 04:47:20
【问题描述】:

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

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

我意识到我真正需要的不是在无法获得共享锁或升级锁的情况下进行阻塞。不幸的是,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
}

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    答案似乎是您可以提供 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.
    }
    

    编辑: 我还通过实验发现,如果您没有升级锁,则 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 再调用 unlock 否则您会抛出一个锁定异常。 你当然可以让 unique_lock 和 write_lock 超出范围,从而释放锁,尽管我发现有时你想提前释放它,你应该在这种状态下花费最少的时间。

    【讨论】:

      猜你喜欢
      • 2011-04-23
      • 2013-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多