在示例代码中condition variable ,它表明:
在worker
线程拥有mutex(唯一锁)后,然后等待。
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
main
线程仍然可以获得互斥量(锁守卫)。
{
std::lock_guard<std::mutex> lk(m);
ready = true;
}
这是否意味着 lock_guard 可以拥有一个由 unique_lock 拥有的互斥体?
最佳答案
不,这意味着在 wait
期间互斥锁被解锁以允许提供者线程锁定它并拥有对 cv 的权限。您在所引用的示例代码中省略了最重要的行,notify_one
:
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one(); // wake up the waiting thread
这就是为什么您需要为 wait
提供锁,这样它就可以在 sleep 前解锁它并在它醒来后尝试重新锁定它。
从您链接的页面的第一部分,尤其是注释 2 和 3:
Any thread that intends to wait on std::condition_variable has to
- acquire a std::unique_lock, on the same mutex as used to protect the shared variable
- execute wait, wait_for, or wait_until. The wait operations atomically release the mutex and suspend the execution of the thread.
- When the condition variable is notified, a timeout expires, or a spurious wakeup occurs, the thread is awakened, and the mutex is atomically reacquired. The thread should then check the condition and resume waiting if the wake up was spurious.
关于C++ 线程 : can lock_guard own a mutex that owned by a unique_lock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315967/