Thread synchronization in C Sharp

Synchronization: It is a technique that where another thread can share the piece of code (critical section) , only if the current thread complete its execution.
No other thread can enter into the critical section , until the current thread finishes its execution and come out from the critical section.

In multi threaded environment threads can share any resource and executes asynchronously.
Some times asynchronous execution may halt the system.
To avoid this we can go with thread synchronization where only one can share the resource until its execution completed or releasing the resource.

Advantage of synchronization.

–To avoid the deadlock.
— To maintain Consistency.

Look at the Output of below program on console. You should find the unwanted output i.e. mixture of both strings.

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
    {
        static void Main(string[] args)
        {
            //Both thread will print a same string on console.
            Thread t1 = new Thread(printer);
            Thread t2 = new Thread(printer);
            t1.Start();
            t2.Start();
            t2.Join();

        }

        static void printer()
        {
            String arr = "finesrc is the excellent resource for interview preparation!!!";

            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i]);
            }
        }
    }

Output

finesrc is the excellent resourfinesrc is the excellent resource for intce for i
erview preparation!!!nterview preparation!!!

if we observe the output of the above program it is a mixture of unwanted output i.e mixture of both strings.

To avoid unwanted mixture other thread needs to share the resource only after execution of current thread. This kind of context switching we can achieve through thread synchronization.

Thread synchronization can be achieved with the following categories.

  • Simple blocking methods -Sleep, Join, and Task.Wait
  • Locking constructs – exclusive locks(lock, mutex, spinlock,monitor), and non exclusive locks (semaphore, semaphore slim, and read/writer locks)
  • Signaling constructs -event wait handles, Monitor’s Wait/Pulse, CountdownEvent and Barrier classes.
  • Non blocking synchronization constructs – Thread.MemoryBarrier, Thread.VolatileRead, Thread.VolatileWrite, the volatile keyword, and the Interlocked class.

We will discuss all the above mechanisms in later session, first we will concentrate on lock to achieve synchronization.

Thread synchronization C# example

When we synchronize the code block of printer() function where printing is going on console, program will print the correct string for both threads on the console.

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
    {
        //Object lock to lock the crtical section/ shared resource.
        //cmd console is the shared resource here.
        private static Object lockCode = new Object();

        static void Main(string[] args)
        {
            //Both thread will print a same string on console.
            Thread t1 = new Thread(printer);
            Thread t2 = new Thread(printer);

            t1.Start();
            t2.Start();
            t2.Join();

        }

        static void printer()
        {
            String arr = "finesrc is the excellent resource for interview preparation!!!";

            //Synchronize the code for printing string on console.
            lock (lockCode)
            {

                for (int i = 0; i < arr.Length; i++)
                {
                    Console.Write(arr[i]);
                }
            }
        }
    }

Output

finesrc is the excellent resource for interview preparation!!!finesrc is the exc
ellent resource for interview preparation!!!

 

In the above program we have used Object lock to synchronize the code block in printer () function where threads are printing strings on same console.