I'm much confused by this description of monitor on Wiki, which says:
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.
My question is: this seems exactly what cond.wait(locker, [](){return !q.empty();});
does in C++. Why this is called monitor? Are they the same? Thanks!
mutex mu;
condition_variable cond;
...
unique_lock<mutex> locker(mu);
cond.wait(locker, [](){return !q.empty();});
If I understand correctly, a monitor is an object that has a condition variable associated with it (and a mutex, as the condition variable depends on that), allowing threads to either wait on the condition variable or notify another thread through the condition variable.
In Java, every Object
is a monitor. In C++, you have to set it up yourself by defining a mutex
and condition_variable
, and explicitly locking the mutex
(with unique_lock
) before you call wait()
.
In other words, monitor is a concept, while condition variable is an implementation detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With