Junior — Middle
What is the difference between the mutual exclusion mechanisms Lock and Semaphore when managing access to resources?
sobes.tech AI
Answer from AI
Lock (mutual exclusion) and Semaphore are synchronization mechanisms, but they differ in functionality and application:
-
Lock (Mutex)
- Designed to provide exclusive access to a resource.
- Only one thread can own the Lock at a time.
- If the Lock is occupied, other threads wait for it to be released.
- Used to protect critical sections.
-
Semaphore
- Has a counter that determines how many threads can access the resource simultaneously.
- Can allow multiple threads to access at the same time (for example, a semaphore with a counter of 3 allows 3 threads at once).
- Used to manage access to a limited number of resources.
Example in C#:
// Mutex
Mutex mutex = new Mutex();
mutex.WaitOne(); // acquire
// critical section
mutex.ReleaseMutex(); // release
// Semaphore
Semaphore semaphore = new Semaphore(3, 3); // maximum 3 concurrent accesses
semaphore.WaitOne();
// work with resource
semaphore.Release();
Thus, Lock is a special case of a semaphore with a maximum counter of 1.