Sobes.tech
Junior — Middle

Millised on vahetus välistamise Lock ja Semaphore mehhanismide erinevused ressurssidele juurdepääsu haldamisel?

sobes.tech AI

Vastus AI-lt

Lock (mutual exclusion) and Semaphore (semaphore) are synchronization mechanisms, but they differ in functionality and application:

  • Lock (Mutex)

    • Designed to ensure 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 to access simultaneously).
    • Used to manage access to limited 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();

Therefore, Lock is a special case of semaphore with a maximum counter of 1.