What is the difference between a mutex and a semaphore?
Interview preparation resource from Gate Smashers.
A mutex is an ownership-based lock used to protect a critical section. A semaphore is an atomic counter used to represent available resources or signal events between tasks.
A mutex normally has two states: locked and unlocked. The thread that locks it is expected to unlock it. This ownership rule makes a mutex suitable for protecting shared data and lets implementations provide features such as priority inheritance.
A counting semaphore can allow up to N users of a resource, while a binary semaphore has values similar to zero and one. Semaphores do not require the same task to perform wait and signal, so they can also coordinate producer-consumer and event-notification workflows.
A mutex is normally preferred when a specific thread must own and release a lock. A semaphore is useful when access is controlled by a count, such as allowing only five tasks to use a resource pool. Both require careful use to avoid deadlock and starvation.
