Junior — Middle
What is the difference between using a semaphore and a mutex for thread synchronization?
sobes.tech AI
Answer from AI
Mutex (mutual exclusion) is a synchronization primitive that provides exclusive access to a resource: only one thread can own the mutex at a time.
Semaphore is a more general primitive that allows limiting the number of threads that can access a resource simultaneously. The semaphore's value is a count of permits.
Main differences:
- Mutex is a semaphore with a maximum value of 1.
- Mutex provides mutual exclusion, semaphore limits parallelism.
Example:
- Mutex is used to protect a critical section so that only one thread executes it.
- Semaphore can be used to limit the number of threads working with a connection pool (for example, a maximum of 5).
Thus, mutex is a special case of semaphore with a single permit.