Question

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

Was it helpful?

Solution

For example in C# .NET 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.

Edit: In later versions of the .NET framework, this was changed to:

bool lockTaken = false;
try
{
    Monitor.Enter(object, ref lockTaken);
    // Your code here...
}
finally
{
    if (lockTaken)
    {
        Monitor.Exit(object);
    }
}

OTHER TIPS

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.

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.

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).

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.

There is no difference, lock generates Monitor.Enter and Monitor.Exit within a try/finally block. Using Monitor over lock allows you to fine tune because it has Pulse and PulseAll. You can also have alternate processing should you be unable to acquire the lock with TryEnter.

Lock focus on only mutual exculsion, but Moniter provides mutual exclusion automatically.

So we don't need to worry of using mutual exclusion in Monitor. Instead of ME, we need to consern of sycronzing only when we do programming.

Moniter provides more systematical way of programming. It, therefor, is more advanced one.

Monitor is the concept and Lock is the actual implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top