C# Mutex, Semaphore, Thread Signaling

C# Code Snippets Mutex Semaphore Thread Signaling


In this code snippet, we will see some more ways of doing thread synchronization in C#. We’ll look at mutex, semaphore, and thread signaling(ManualResetEvent/AutoResetEvent).

You can find out what thread synchronization is and why it’s needed in this post. Here I will only show a few more ways of doing it.

Mutex(mutual exclusion) is very similar to lock/Monitor. The difference is that it can work across multiple processes.

A semaphore is very similar to lock/Monitor. The difference is that it can allow for a specified amount of threads to work with the same resources at the same time. The way it works is the Semaphore class has an integer variable. When the class is instantiated the variable is initialized to the max number of threads that will be allowed to access a resource. When the value of this variable is 0 no more threads are allowed to access the resources being locked. When a thread enters a lock(WaitOne()) it will decrement the said variable by one and when it exits the lock(Release()) it will increase it by one.

Thread Signaling using Auto/ManualResetEvent
Thread signaling is yet another way of doing thread synchronization. When the child thread hits the WaitOne() method it will wait there until the main thread signals it to continue by using the set() method.

For more information and other thread synchronization methods see Microsoft documentation here. Sometimes you can also avoid having to deal with thread synchronization by using thread-safe classes. So make sure you consult the documentation to see if the class you are using is thread-safe(or if you can find a thread-safe alternative). You might just save yourself some work.

Let’s have a look at the code below to see how to do thread synchronization.

1.1 ManualResetEvent

Mutex Code:

Resulting output:

Semaphore Code:

Resulting output:

Thread Signaling Code:

Resulting output:

1.1 ManualResetEvent
C# ManualReset Event resulting output
ManualResetEvent resulting output

2.1 AutoResetEvent

AutoResetEvent calling set() only once resulting output

2.1 AutoResetEvent

C# AutoResetEvent resulting output 2
AutoResetEvent calling set() twice resulting output

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger