代码之家  ›  专栏  ›  技术社区  ›  hookenz

使用scoped try_shared_lock和upgrade lock in boost的示例

  •  2
  • hookenz  · 技术社区  · 14 年前

    我有一个线程池正在使用Boost库中的共享互斥体。

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

    我意识到,如果无法获得共享锁或升级锁,我实际上需要的不是阻止。不幸的是,Boost文档缺少任何正在使用的示例。

    有人能给我指一下或提供一个例子,具体说明这种方式使用的共享锁。

    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 回复  |  直到 14 年前
        1
  •  8
  •   hookenz    14 年前

    答案似乎是您可以提供增强:尝试将锁定作为这些作用域锁中的几个的参数。

    例如

    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.
    }
    

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

    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超出范围,从而释放锁,尽管我发现有时您希望更早地释放它,您应该在这种状态下花费最少的时间。