Thread Synchronization with Barrier Construct

What is Barrier and how to synchronize threads using Barrier


Category: Multithreading Tags: C#


Introduction

        Barrier construct can be used to synchronize several threads to meet at same point in time. This construct is useful for multi-threaded algorithms which executes some functionality after each iteration.

Implementation

    See code below:

class Program
{
    static Barrier barrier = new Barrier(2, x => Console.WriteLine("End of phase {0}", x.CurrentPhaseNumber + 1));
    static void Main(string[] args)
    {
        Thread t1 = new Thread(() => Print("thrad 1", "printing", 2));
        t1.Name = "t1";

        Thread t2 = new Thread(() => Print("thrad 2", "printing", 3));
        t2.Name = "t2";

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

        Console.ReadLine();
    }

    static void Print(string name, string message, int seconds)
    {
        for (int i = 1; i < 3; i++)
        {
            Console.WriteLine("---------------------------------------------");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("{0} started {1}", name, message);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("{0} finished {1}", name, message);
            barrier.SignalAndWait();
        }
    }
}

Above we can see barrier constructor takes two parameters one is participantCount(number of threads) and other one is postPhaseAction(callback method). In our case participantCount is 2 because two threads we want to synchronize, and postPhaseAction defines a callback function. Print method runs loop twice and two times barrier signals using SignalAndWait method so there would be two phases in each thread. When both threads have signaled then only callback method executes. In above code waiting time for t1 is 2+2=4 seconds in each loop iteration and waiting time for thread t2 is 3+3=6 seconds in each loop iteration so t1 signals 6-4=2 seconds before t2 but call back will not be executed until t1 and t2 both signals. When both thread send signal then it will be called as a phase. Output of the code will be:
---------------------------------------------
---------------------------------------------
thrad 1 started printing
thrad 2 started printing
thrad 1 finished printing
thrad 2 finished printing
End of phase 1
---------------------------------------------
---------------------------------------------
thrad 1 started printing
thrad 2 started printing
thrad 1 finished printing
thrad 2 finished printing
End of phase 2


Like 0 People
Last modified on 15 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 132
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x