StartUp Interview QuestionDeveloper Program Engineers
Interview Type: Phone Interview
Mutex has ownership while Semaphore doesn't. What it means is that when a thread "locks" mutex it acquires ownership of mutex and its same thread that must "unlock" mutex and relinquish its ownership. This helps in achieving mutual exclusion
Semaphore on the other hand doesn't have ownership. Semaphore is a counter, and any thread that doesn't own a Semaphore can "signal" or increment its value. Semaphore is basically a "signalling" mechanism, imagine a process is waiting for some sort of event and it is "signalled" that event has happened, a semaphore can keep count of number of occurrences of such events. Semaphore is thus IPC mechanism
A mutex is a lock that a process can acquire or lock. You can use it to prevent multiple processes from entering the same critical region (ie. running a certain piece of code). For example, if you have a hash table you can use mutex to ensure only 1 process will update this hash table at any given time.- Sunny December 04, 2013
Semaphore is basically a counter, where processes can increment or decrement, except it will stall the process if it tries to decrement below zero. For example, when you have multiple resources, you can use a semaphore to keep track of the number of available resources. When a process needs a resource it can decrement the semaphore and increment it when the process no longer needs it. A process trying to decrement the semaphore when it's zero (meaning no more free resource) will stall until it gets incremented.