Explain the differences between lock, Semaphore, and Mutex locking mechanisms.
sobes.tech AI
Answer from AI
In C#, there are different synchronization mechanisms for managing access to shared resources in a multithreaded environment:
-
lock — is syntactic sugar for using
Monitor.EnterandMonitor.Exit. It provides exclusive access to a block of code to one thread. If another thread tries to enter this block, it will wait until the lock is released. -
Mutex — is a synchronization object that can be used for inter-process communication. Mutex can be global and used for synchronization between different processes, whereas
lockonly works within a single process. Mutex is more expensive in terms of performance than lock. -
Semaphore — is a counter that limits the number of threads that can access a resource simultaneously. For example,
Semaphore(3)allows up to three threads to work with the resource at the same time. Semaphore is useful when a resource can serve multiple threads but with a limit.
Summary:
lock— simple and fast mechanism for exclusive access within a process.Mutex— for exclusive access, including inter-process.Semaphore— to limit the number of threads working with a resource simultaneously.
Example of using lock:
private readonly object _lockObj = new object();
void CriticalSection()
{
lock(_lockObj)
{
// code that should be executed by only one thread
}
}