如何在此条件中使用lock_guard

How to use lock_guard in this conditional

本文关键字:lock guard 条件      更新时间:2023-10-16

线程具有以下控制流:

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
}

由于这两种情况下的并行操作都是在解锁保护全局条件的互斥体之后完成的,这意味着条件要么不能改变,要么我们不在乎它是否改变。因此,我们可以保存该值,如果不是,则稍后根据保存的值再次保存。