views:

937

answers:

5

What's the difference between a monitor and a lock?

If a lock is simply an implementation of mutual exclusion, then is a monitor simply a way of making use of the waiting time inbetween method executions?

A good explanation would be really helpful thanks....

regards

+3  A: 

They're related. For example, in C# the lock statement is a simple try-finally wrapper around entering a Monitor and exiting one when done.

Jeff Moser
+4  A: 

A lock statement is equivalent to:

Monitor.Enter(object);
try
{
    // Your code here...
}
finally
{
    Monitor.Exit(object);
}

However, keep in mind that Monitor can also Wait() and Pulse(), which are often useful in complex multithreading situations.

John Gietzen
@John Gietzen: awesome...thx for the great explanation.
dboarman
A: 

Monitors are compiler-assisted "semi-automatic" locks. They allow one to declare synchronized methods on classes, etc. This is just a different approach to providing mutual exclusion. I found this book to be the most thorough explanation of the concepts, even though it's mostly geared towards OS developers.

Nikolai N Fetissov
A: 

A lock ensures mutual exclusion.

A monitor associates the data to be protected and the mutual exclusion and synchronization primitives required to protect accesses to the data.
Synchronization is used e.g. when you need one thread to wait until an event occurs (e.g., wait until another thread places an item in a queue).

Bastien Léonard
A: 

Monitors is a programming-language construct that does the same thing as semiphores/locks, but Monitors control the shared data by synchronizing at run time. In contrast, locks protect the shared data by just "spinning" which can lead to poor CPU utilization.

Dan Mantyla