I have been using an AutoResetEvent to do synchronisation between threads.
However only one of the waiting threads(A-F) is unblocked. - how can i get them ALL to unblock when thread(X) finishes it's work?
I guess I am using the wrong synchronisation primitive - what should i be using and how?
Code samples would be ideal
Is the ManualResetEvent what you are looking for?
It will stay set until it is reset by some thread.
Somewhere in your code you must know when to Reset it. This might be a simple counter or collection of spawned threads.
Suppose you have this code:
class Program
{
static void Main(string[] args)
{
var are = new AutoResetEvent(false);
for (int i = 0; i < 10; i++)
{
var j = i;
new Thread(() =>
{
Console.WriteLine("Started {0}", j);
are.WaitOne();
Console.WriteLine("Continued {0}", j);
}).Start();
}
are.Set();
Console.ReadLine();
}
}
You would then get output such as this:
Started 0
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Continued 0
Started 9
But if you instead use ManualResetEvent
:
class Program
{
static void Main(string[] args)
{
var mre = new ManualResetEvent(false);
for (int i = 0; i < 10; i++)
{
var j = i;
new Thread(() =>
{
Console.WriteLine("Started {0}", j);
mre.WaitOne();
Console.WriteLine("Continued {0}", j);
}).Start();
}
mre.Set();
Console.ReadLine();
}
}
Then you'll get what I guess is the expected behavior:
Started 0
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Started 9
Continued 1
Continued 8
Continued 7
Continued 4
Continued 5
Continued 6
Continued 3
Continued 0
Continued 9
Continued 2
Of course, as the name implies, ManualResetEvent
needs to be manually reset, whereas AutoResetEvent
automatically resets after the first WaitOne
has released its thread.
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