What is the difference between a mutex and a semaphore?
MediumConceptProcess Synchronization
Answer
A mutex (mutual exclusion lock) is a lock with an owner: only one thread can hold it, and the thread that locked it must be the one to unlock it. A semaphore is an integer counter changed only by two atomic operations: wait() (also called P or down) blocks while the value is 0 and then decrements it, and signal() (V or up) increments it and wakes a waiting thread. A semaphore has no owner, so any thread may signal it.
- A binary semaphore (values 0 and 1) can work like a lock, but because it has no owner it is mostly used for signalling, such as one thread telling another that data is ready.
- A counting semaphore that starts at n controls access to n identical resources, such as 3 printers or 10 database connections.
- Ownership lets a mutex detect errors, such as unlocking a lock you do not hold, and support priority inheritance.
Example: a car park with 3 spaces behaves like a counting semaphore initialised to 3. Cars 1–3 call wait() (3 → 2 → 1 → 0) and park; car 4 blocks until a car leaves and calls signal(). A single washroom key is a mutex: one person holds it, and that same person returns it.