Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between lock and Mutex?

What is the difference between lock and Mutex? Why can't they be used interchangeably?

like image 493
Ram Avatar asked Sep 17 '10 12:09

Ram


People also ask

What is the difference between mutex lock and semaphore?

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.

What is the difference between lock and 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.

Is mutex a lock?

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

Why do we use mutex lock?

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.


2 Answers

A lock is specific to the AppDomain, while Mutex to the Operating System allowing you to perform inter-process locking and synchronization (IPC).

like image 137
Darin Dimitrov Avatar answered Sep 30 '22 02:09

Darin Dimitrov


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.

like image 40
Toby Avatar answered Sep 30 '22 04:09

Toby