调用函数时,unique_lock是否已解锁?

ada*_*ife 1 c++ multithreading mutex

假设我有这样的情况:

void consumer(){
   unique_lock<mutex> lock(mtx);
   foo();  
}

void foo(){
    /* does the thread still own the mutex here? */
}
Run Code Online (Sandbox Code Playgroud)

我希望可以,但是我不确定100%。

Som*_*ken 6

unique_lock通话的析构函数mtx.unlock()。析构函数在锁的生存期结束时被调用。通常(请参见注释),锁的生存期结束为:

void consumer(){
   unique_lock<mutex> lock(mtx);
   foo();  
} // <- here.
Run Code Online (Sandbox Code Playgroud)

是的,它仍然会被锁定。