我可以boost::lock_guard
用来获取boost::mutex
对象上的锁,这种机制将确定一旦boost::lock_guard
超出范围,锁将被释放:
{
boost::lock_guard<boost::mutex> lock(a_mutex);
// Do the work
}
在这种情况下,a_mutex
无论代码块是否被异常退出,都会被释放。
另一方面, aboost::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
}
如果语句块因异常退出,unlock()
则此代码不会。a_timed_mutex
true
if
问题: Boost(据我所知,C++11 标准都不是)似乎没有提供lock_guard
与try_lock()
or一起使用的变体try_lock_for(period)
。处理第二种情况的“推荐”方式或最佳实践是什么?