C++ 线程 : can lock_guard own a mutex that owned by a unique_lock?

标签 c++ multithreading

在示例代码中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

  1. acquire a std::unique_lock, on the same mutex as used to protect the shared variable
  2. execute wait, wait_for, or wait_until. The wait operations atomically release the mutex and suspend the execution of the thread.
  3. 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/

相关文章:

c++ - 拆分临界区并两次锁定互斥量是否有助于提高性能?

c++ - C/C++ 功能/系统测试的测试框架?

c++ - 是否可以声明一个指向具有未知(在编译时)返回类型的函数的指针

multithreading - 共享内存计算机上的多线程 FFTW 3.1.2

javascript - 运行 Node.js 是在浪费多核 CPU 吗?

java - 如何检查该池 'reuses' 线程

android - 使用 AsyncTask 打开相机

c++ - dwPageSize 和 dwAllocationGranularity 之间的关系

c++ - 如何打印 R、G 和 B 矩阵

c++ - 使嵌套的 if-else 更易于管理和高效