【问题标题】:How to use a lock_guard with try_lock_for如何将 lock_guard 与 try_lock_for 一起使用
【发布时间】:2014-04-19 06:58:36
【问题描述】:

我可以使用boost::lock_guard 来获取boost::mutex 对象上的锁,这种机制将确定一旦boost::lock_guard 超出范围,锁就会被释放:

{
  boost::lock_guard<boost::mutex> lock(a_mutex);
  // Do the work
}

在这种情况下,无论代码块是否因异常退出,a_mutex 都会被释放。

另一方面,boost::timed_mutex 也支持方法try_lock_for(period),例如

if(a_timed_mutex.try_lock_for(boost::chrono::seconds(1))) {
  // Do the work
  a_timed_mutex.unlock(); // <- This is needed!
} else {
  // Handle the acquisition failure
}

如果if 语句的true 块因异常退出,则此代码不会unlock() a_timed_mutex

问题: Boost(据我所知,C++11 标准都不是)似乎没有提供与 try_lock() 或 @ 一起使用的 lock_guard 的变体987654335@。处理第二种情况的“推荐”方式或最佳实践是什么?

【问题讨论】:

    标签: c++ boost boost-mutex


    【解决方案1】:

    你可以在加锁后创建锁守卫,告诉它采用锁:

    if(a_timed_mutex.try_lock_for(boost::chrono::seconds(1))) {
      boost::lock_guard<boost::mutex> lock(a_timed_mutex, boost::adopt_lock_t());
      // Do the work
    } else {
      // Handle the acquisition failure
    }
    

    标准lock_guard 也允许这样做。

    【讨论】:

      【解决方案2】:

      尝试 unique_lock, unique_lock::try_lock_for()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-02
        • 1970-01-01
        • 2023-03-13
        • 2014-09-25
        • 2016-01-30
        相关资源
        最近更新 更多