This is one of the most famous question of Microsoft interviews and Engineering vivas and one must know bit of internals as well
Mutex: These are typically used to serialize access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section.
It is locking mechanism used to synchronize access to a resource. Only one task\ Thread can acquire the mutex. It means there will be ownership associated with mutex, and only the owner can release the lock (mutex) unless its a recurring mutex else it will result deadlock
Famous Toilet example on Mutex: Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.
Semaphore: This restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource.
It is signaling mechanism (“I am done, you can carry on” kind of signal). In case another thread want to use resource an interrupt will be triggered upon which an interrupt service routine (ISR) will signal the call processing task to wakeup.
Famous Toilet example on Semaphore: say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Key Points:
- A thread can acquire more than one lock (Mutex).
- A mutex can be locked more than once only if its a recursive mutex, here lock and unlock for mutex should be same
- If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock.
- Binary semaphore and mutex are similar but not same.
- Mutex is costly operation due to protection protocols associated with it.
- Main aim of mutex is achieve atomic access or lock on resource
Myth:
Couple of article says that "binary semaphore and mutex are same" or "Semaphore with value 1 is mutex" but the basic difference is Mutex can be released only by thread that had acquired it, while you can signal semaphore from any other thread
Very clearly articulated in simple terms.
ReplyDelete