RAII 带条件锁定

RAII locking with condition

我有一段代码只有在某些条件为真时才需要用锁来保护。

if(condition) {

   std::lock_guard<std::mutex> guard(some_mutex);

   // do a bunch of things

} else {

   // do a bunch of things
}

虽然我可以将所有 // bunch of things 移动到一个单独的函数中并调用它,但我想知道是否有允许有条件地获取锁的 RAII 方法。

类似

if(condition){

   // the lock is taken
}

// do a bunch of things

// lock is automatically released if it was taken

您可以切换到使用 std::unique_lock and use its std::defer_lock_t tagged constructor. This will start with the mutex unlocked, but you can then use its lock() 方法来锁定互斥体,然后由析构函数释放。这会给你一个看起来像这样的代码流:

{
    std::unique_lock<std::mutex> guard(some_mutex, std::defer_lock_t{});
    if (mutex_should_be_locked)
    {
        guard.lock();
    }
    // rest of code 
} // scope exit, unlock will be called if the mutex was locked