What is the difference between lock and Mutex? Why can't they be used interchangeably?
A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.
Lock vs SemaphoreLocks cannot be shared between more than one thread processes but semaphores can have multiple processes of the same thread. Only one thread works with the entire buffer at a given instance of time but semaphores can work on different buffers at a given time.
Strictly speaking, a mutex is a locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there is ownership associated with a mutex, and only the owner can release the lock (mutex).
Mutex lock will only be released by the thread who locked it. So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.
A lock is specific to the AppDomain, while Mutex to the Operating System allowing you to perform inter-process locking and synchronization (IPC).
lock
is a compiler keyword, not an actual class or object. It's a wrapper around the functionality of the Monitor
class and is designed to make the Monitor
easier to work with for the common case.
The Monitor
(and the lock
keyword) are, as Darin said, restricted to the AppDomain
. Primarily because a reference to a memory address (in the form of an instantiated object) is required to manage the "lock" and maintain the identity of the Monitor
The Mutex
, on the other hand, is a .Net wrapper around an operating system construct, and can be used for system-wide synchronization, using string data (instead of a pointer to data) as its identifier. Two mutexes that reference two strings in two completely different memory addresses, but having the same data, will actually utilize the same operating-system mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With