What is the Mutex and semaphore in C#? Where we need to implement?
How can we work with them in multithreading?
(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.
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.
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.
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.
You should start at MSDN.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With