如何将lock_guard与try_lock_for一起使用

How to use a lock_guard with try_lock_for

本文关键字:lock for 一起 try guard      更新时间:2023-10-16

我可以使用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()try_lock_for(period)一起工作的lock_guard变体。处理第二种情况的"推荐"方法或最佳实践是什么?

您可以在锁定后创建锁保护,告诉它采用锁:

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也允许这样做。

try unique_lock,unique_lock::try_lock_for()