Sobes.tech
Middle

Mutex va semafor nima farq qiladi?

sobes.tech AI

AIdan javob

lock in C# is syntactic sugar for using Monitor.Enter and Monitor.Exit, wrapped in a try-finally block to ensure the lock is released. It provides exclusive access to a resource for a single thread. Essentially, it is the simplest synchronization primitive at the object level.

Mutex is a synchronization primitive that can be used to provide exclusive access to a resource for a single thread across multiple processes. It has a concept of thread ownership: only the thread that has acquired the mutex can release it.

Semaphore is a synchronization primitive that limits the number of threads that can access a resource simultaneously. It has a counter that decreases when access is acquired and increases when released.

The main differences are presented in the table:

Characteristic lock (Monitor) Mutex Semaphore
Visibility scope Within a single process Between processes Between processes
Number of threads Only one Only one (owner) Limited number
Ownership Thread-bound Thread-bound Not thread-bound
Usage Simple synchronization Synchronization between processes, named mutexes Limiting parallel access to a resource
Exceptions Does not require explicit handling of AbandonedMutexException Requires handling of AbandonedMutexException No AbandonedSemaphoreException
// Example of using lock
private readonly object _lockObject = new object();

public void DoSomethingWithLock()
{
    lock (_lockObject)
    {
        // Critical section
    }
}

// Example of using Mutex
using System.Threading;

private Mutex _mutex = new Mutex();

public void DoSomethingWithMutex()
{
    _mutex.WaitOne(); // Acquire mutex
    try
    {
        // Critical section
    }
    finally
    {
        _mutex.ReleaseMutex(); // Release mutex
    }
}

// Example of using Semaphore
using System.Threading;

private Semaphore _semaphore = new Semaphore(3, 3); // Allows 3 threads at once

public void DoSomethingWithSemaphore()
{
    _semaphore.WaitOne(); // Acquire "access" to semaphore
    try
    {
        // Critical section, limited to 3 threads
    }
    finally
    {
        _semaphore.Release(); // Release "access"
    }
}