如何在此条件中使用lock_guard
How to use lock_guard in this conditional
线程具有以下控制流:
mutex.lock()
if (condition) {
// do synced things
mutex.unlock();
// do parallel things
} else {
// do other synced things
mutex.unlock();
// do other parallel things
}
注意do
的四个部分是如何执行不同的事情的。
如何将锁定和解锁的直接调用替换为使用std::lock_guard
?
std::unique_lock
看起来像您想要的。语义类似于std::lock_guard
,但允许更复杂的构造。因此,在您的情况下,您仍然可以获得异常安全性,但也可以明确提前解锁。类似于:
std::unique_lock<decltype(mutex)> guard(mutex); // calls mutex.lock() like lock_guard
if (condition) {
// do synced things
guard.unlock();
// do parallel things
} else {
// do other synced things
guard.unlock();
// do other parallel things
}
// unlocks on leaving scope, if held similar to lock_guard
bool cond;
{
std::lock_guard<std::mutex> lg(mutex);
cond = global_condition;
if (cond){
// do some synced stuff
} else {
// do the other synced stuff
}
}
if (cond){
// do parallel stuff
} else {
// do the other parallel stuff
}
由于这两种情况下的并行操作都是在解锁保护全局条件的互斥体之后完成的,这意味着条件要么不能改变,要么我们不在乎它是否改变。因此,我们可以保存该值,如果不是,则稍后根据保存的值再次保存。
相关文章:
- 尝试构建"lock-free"数据结构C++
- 为什么 c++11 std::lock 和 std::scoped_lock 至少需要 2 个参数?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- DRD 报告"conflicting load" std::mutex::lock 上的错误
- 在 std::tie 中使用 std::weak_ptr::lock()
- std::lock_guard 怎么可能比 std::mutex::lock() 更快?
- std::mutex::lock() 产生奇怪(和不必要的)ASM 代码
- "lock cmpxchg"如何在装配中工作?
- std::lock 仍然导致死锁
- 在任何地方对C++中所有并行线程中的所有锁定和解锁实例使用相同的 std::mutex 和 lock 对象
- 我们是否需要对多线程 x32 系统使用 lock 来读取或写入 uint32_t 变量
- 使用Mutex,lock_guard,在课堂中正确地lock
- 我什么时候不希望在Visual Studio中启用“Control Flow Guard Microsoft
- 正在解锁手动未定义/不良设计的锁定guard
- 当我调用lock()时,为什么std :: mutex会引发异常
- clang-tidy llvm-header-guard目录配置
- mutex.lock vs unique_lock
- 使用 std::lock (c++11) 的大量 CPU 负载
- 我是否必须使用neak_ptr.lock()只是为了测试它是否指向有效的对象
- std::lock() equivalent for boost::shared_mutex?