Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Mutex and semaphore In c#? where we need to implement? [closed]

Tags:

What is the Mutex and semaphore in C#? Where we need to implement?

How can we work with them in multithreading?

like image 867
Jaswant Agarwal Avatar asked Oct 12 '09 06:10

Jaswant Agarwal


People also ask

What is a mutex in C?

(since C++11) The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

What is semaphore in C?

A semaphore is a data structure used to help threads work together without interfering with each other. The POSIX standard specifies an interface for semaphores; it is not part of Pthreads, but most UNIXes that implement Pthreads also provide semaphores. POSIX semaphores have type sem_t.

Which is better mutex or semaphore?

If you have number of instances for resource it is better to use Binary semaphore. If you have single instance for resource it is better to use mutex.

Why mutex is used in semaphore?

Mutex allows multiple program threads to access a single resource but not simultaneously. Semaphore allows multiple program threads to access a finite instance of resources. Mutex object lock is released only by the process that has acquired the lock on the mutex object.


2 Answers

You should start at MSDN.

  • System.Threading.Mutex: A synchronization primitive that can also be used for interprocess synchronization.
  • System.Threading.Semaphore: Limits the number of threads that can access a resource or pool of resources concurrently.

Generally you only use a Mutex across processes, e.g. if you have a resource that multiple applications must share, or if you want to build a single-instanced app (i.e. only allow 1 copy to be running at one time).

A semaphore allows you to limit access to a specific number of simultaneous threads, so that you could have, for example, a maximum of two threads executing a specific code path at a time.

like image 143
bobbymcr Avatar answered Oct 15 '22 06:10

bobbymcr


I'd start by reading this: http://www.albahari.com/threading/part2.aspx#_Synchronization_Essentials and then bolster it with the MSDN links bobbymcr posted.

like image 24
Ed Power Avatar answered Oct 15 '22 07:10

Ed Power