I've been asked the following question and I'm not sure what the correct answer is to it:
If monitors are implemented by replacing condition variables with semaphores
(counters set to 0) with down() and up() as wait and signal, respectively,
would the monitors work correctly?
I'd be tempted to say it is a correct implementation because semaphores and condition variables can replace each other, correct? Is there a better explanation?
You are asking about a semaphore initialized to 1, which is also called a binary semaphore.
The answer depends on a particular implementation (or definition) of these primitives, however a typical difference is that monitors have thread ownership and semaphores do not. This impacts a variety of scenarios.
A
internally calls public methodB
. Then a recursive monitor will correctly allow calling methodA
(which involves a sequence lock-lock-unlock-unlock) whereas the same with a semaphore-implemented monitor would result in a deadlock upon the second attempt to lock, using the same thread.So, a binary semaphore is similar to a monitor, but do not expect it to behave identically.