如何将lock_guard与try_lock_for一起使用
How to use a lock_guard with try_lock_for
我可以使用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()
相关文章:
- "error: no matching function for call to"构造函数错误
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何在C++中从两个单独的for循环中添加两个数组
- 在Linux for Windows上编译C++代码时出错
- 调用专用模板时出错"no matching function for call to [...]"
- 为什么我的for循环不能正确获取argv
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- std::memory_order for std::atomic:<T>:wait
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- std::lock() equivalent for boost::shared_mutex?