Difference between lock and monitor?
A lock encapsulates a monitor; it is effectively the same as writing:
Monitor.Enter(myObject);
try
{
// Your code here...
}
finally
{
Monitor.Exit(myObject);
}
Most of the time, lock is all you need, but monitor allows other bits and bobs, such as the Wait and Pulse methods, which can help when multithreaded apps get complicated.
Mutex
A Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wideas well as application-wide.
Acquiring and releasing an uncontended Mutex takes a few microseconds — about 50 times slower than a lock.
Semaphore
A semaphore is like a nightclub: it has a certain capacity, enforced by a bouncer. Once it’s full, no more people can enter, and a queue builds up outside. Then, for each person that leaves, one person enters from the head of the queue. The constructor requires a minimum of two arguments: the number of places currently available in the nightclub and the club’s total capacity.
A semaphore with a capacity of one is similar to a Mutex or lock, except that the semaphore has no “owner” — it’s thread-agnostic. Any thread can call Release on a Semaphore, whereas with Mutex and lock, only the thread that obtained the lock can release it.
There are two functionally similar versions of this class: Semaphore and SemaphoreSlim. The latter was introduced in Framework 4.0 and has been optimized to meet the low-latency demands of parallel programming.
No comments:
Post a Comment