0Ni*_*las 1 c++ multithreading locking raii
我有一段代码,仅当某些条件成立时才需要用锁保护。
if(condition) {
std::lock_guard<std::mutex> guard(some_mutex);
// do a bunch of things
} else {
// do a bunch of things
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以将所有这些移动// bunch of things 到一个单独的函数中并调用它,但我想知道是否有一种 RAII 方法可以允许有条件地获取锁定。
就像是
if(condition){
// the lock is taken
}
// do a bunch of things
// lock is automatically released if it was taken
Run Code Online (Sandbox Code Playgroud)
您可以切换到使用 astd::unique_lock并使用其std::defer_lock_t标记的构造函数。这将从互斥体解锁开始,但您可以使用其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
Run Code Online (Sandbox Code Playgroud)