我对 Wiki 上关于监视器的描述感到很困惑,它说:
A monitor consists of a mutex (lock) object and condition variables. A condition variable is basically a container of threads that are waiting on a certain condition. Monitors provide a mechanism for threads to temporarily give up exclusive access in order to wait for some condition to be met, before regaining exclusive access and resuming their task.
我的问题是:这似乎正是 cond.wait(locker, [](){return !q.empty();});
在 C++ 中所做的。为什么这叫做监视器?它们相同吗?谢谢!
mutex mu;
condition_variable cond;
...
unique_lock<mutex> locker(mu);
cond.wait(locker, [](){return !q.empty();});
最佳答案
如果我理解正确,监视器 是一个对象,它有一个与之相关联的条件变量(和一个互斥锁,作为条件变量取决于此),允许线程等待条件变量或通过条件变量通知另一个线程。
在 Java 中,每个 Object
都是一个监视器。在 C++ 中,您必须通过定义 mutex
和 condition_variable
并显式锁定 mutex
(使用 unique_lock
) 在调用 wait()
之前。
也就是说,监控是一个概念,而条件变量是一个实现细节。
关于c++ - 监视器和条件变量,它们是一样的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31331724/