我有一段代碼,只有在某些條件為真時才需要用鎖保護。
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
uj5u.com熱心網友回復:
您可以切換到使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/450261.html
