我有一段代码,只有当某些条件为true时,它才需要用锁来保护。
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
并使用其带有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