我有一段代码,只有在某些条件为真的情况下,才需要被锁保护。
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发布于 2022-03-25 21:49:12
您可以切换到使用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 lockedhttps://stackoverflow.com/questions/71623389
复制相似问题