Middle
What is the difference between a semaphore and a mutex?
sobes.tech AI
Answer from AI
Mutex (Mutual Exclusion) is a synchronization mechanism that guarantees that only one thread at a time has access to a critical section of code or resource. It operates on the ownership principle: the thread that locks the mutex must unlock it.
Semaphore is a more general synchronization mechanism that manages access to a resource limited by a certain number of "permits". Threads can acquire a permit if available and continue execution. When the resource is no longer needed, the permit is released. Semaphores do not have an ownership concept; any thread can increase the semaphore's count.
Key differences:
- Purpose: Mutex is used for exclusive access (one thread), semaphore for managing access to a limited pool of resources (multiple threads up to a limit).
- Ownership: Mutex has an owner (the thread that locked it). Semaphore has no owner.
- Counter: Mutex can be considered as a semaphore with a counter of 1. Semaphore can have a counter greater than 1.
- Operations: Mutex:
WaitOne/Pulse/ReleaseMutex. Semaphore:WaitOne/Release.
Here's a simple example of using a semaphore in C#:
// Create a semaphore with initial and maximum count of 2.
// Allows 2 threads to access the resource simultaneously.
SemaphoreSlim semaphore = new SemaphoreSlim(2, 2);
// Thread attempts to access the resource
semaphore.WaitOne();
// ... work with the resource ...
semaphore.Release(); // Release the permit
Example of a mutex:
// Create a mutex
Mutex mutex = new Mutex();
// Thread attempts to get exclusive access
mutex.WaitOne();
// ... work with the critical section ...
mutex.ReleaseMutex(); // Release the mutex (only the owner can)