Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

monitor and conditional variable, are they the same?

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();});
like image 851
Sarah Avatar asked Nov 10 '22 09:11

Sarah


1 Answers

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.

like image 189
celticminstrel Avatar answered Nov 15 '22 06:11

celticminstrel