c++ - 在代码的其他部分中使用与 lock_gard 相同的互斥锁是否安全?
问题描述
我有下面的命名空间 func1 和 func2 将从不同的线程中调用。
#include<thread>
namespace test{
std::mutex mu;
void func1(){
std::lock_guard<mutex>lock(mu);
//the whole function needs to be protected
}
void func2() {
mu.lock();
//some code that should not be executed when func1 is executed
mu.unlock();
//some other code
}
}
使用这个互斥锁(一旦使用 lock_guard 和它之外)来保护这些关键部分是否安全?如果不是如何实现这个逻辑?
解决方案
是的,您可以有效地混合和匹配具有不同功能的不同保护实例(例如 lock_guard、unique_lock 等...)std::mutex
。我偶尔遇到的一种情况是,当我想使用std::lock_guard
大多数方法时,但使用 std::condition_variable
期望std::unique_lock
它的wait
方法使用 a。
为了详细说明 Oblivion 所说的内容,我通常会在函数中引入一个新的范围块,以使 ofstd::lock_guard
的使用保持一致。例子:
void func2() {
{ // ENTER LOCK
lock_guard<std::mutex> lck;
//some code that should not be executed when func1 is executed
} // EXIT LOCK
// some other (thread safe) code
}
使用上述模式的优点是,如果任何东西在处于锁定状态的代码的关键部分内引发异常,lck
仍然会调用 的析构函数,从而解锁互斥锁。
推荐阅读
- mysql - 如何在 mysql 查询中将字符串转换为布尔值?
- node.js - Azure Web 应用程序放弃“没有这样的文件或目录错误”
- swift - 这种排序算法存在吗?(在 Swift 中实现)
- python - 如何将两个 tf.data.Dataset 合并为一个,具有已知比率的交替元素
- reactjs - ...this.state 和 this.state 之间的区别
- ios - 如何在 iOS 13 中删除带有外观的导航栏背景?
- javascript - window.scrollTo 在 Safari 上不流畅
- r - R 初学者与极其凌乱的 XLSX 作斗争
- ios - 在集合视图单元格中的 UIView 上设置渐变背景
- r - R中的正则表达式将单词与杂乱语音数据中的语音注释进行匹配