Looking at the Barrier
class , it allows n
threads to rendezvous at a point in time :
static Barrier _barrier = new Barrier(3);
static void Main()
{
new Thread(Speak).Start();
new Thread(Speak).Start();
new Thread(Speak).Start();
}
static void Speak()
{
for (int i = 0; i < 5; i++)
{
Console.Write(i + " ");
_barrier.SignalAndWait();
}
}
//OUTPUT: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4
But so does the CountdownEvent
class :
static CountdownEvent _countdown = new CountdownEvent(3);
static void Main()
{
new Thread(SaySomething).Start("I am thread 1");
new Thread(SaySomething).Start("I am thread 2");
new Thread(SaySomething).Start("I am thread 3");
_countdown.Wait(); // Blocks until Signal has been called 3 times
Console.WriteLine("All threads have finished speaking!");
}
static void SaySomething(object thing)
{
Thread.Sleep(1000);
Console.WriteLine(thing);
_countdown.Signal();
}
// output :
I am thread 3
I am thread 1
I am thread 2
All threads have finished speaking!
So it seems that the Barrier
blocks until n
threads are meeting
while the CountdownEvent
is also blocking until n
threads are signaling.
It's kind of confusing( to me ) to learn from it , when should I use which.
Question:
In which (real life scenario) should I need to choose using Barrier
as opposed to CountdownEvent
(and vice versa) ?