I'm trying to get threads to wait for each other before preceding so they stay in sync.
In my actual program I have lots of IObjectObserved
objects (on their own threads) sending out events and I want to keep everything in sync so an IObjectListener
(on its own thread) can listen to one of these objects 50 times and then subscribe to another in time to catch its 51st event.
I haven't got that far yet, but I think synchronizing threads is the main problem. I'm managed to achieve this with two way signalling using AutoResetEvent
s. Is there not a better way to do this?
class Program
{
static EventWaitHandle _ready = new AutoResetEvent(true);
static EventWaitHandle _go = new AutoResetEvent(false);
static EventWaitHandle _ready1 = new AutoResetEvent(true);
static EventWaitHandle _go1 = new AutoResetEvent(false);
static EventWaitHandle _ready2 = new AutoResetEvent(true);
static EventWaitHandle _go2 = new AutoResetEvent(false);
static void Main(string[] args)
{
new Thread(Waiter).Start();
new Thread(Waiter1).Start();
new Thread(Waiter2).Start();
for (; ; )
{
_ready.WaitOne();
_ready1.WaitOne();
_ready2.WaitOne();
Console.WriteLine("new round");
_go.Set();
_go1.Set();
_go2.Set();
}
}
static void Waiter()
{
for (; ; )
{
_go.WaitOne();
Thread.Sleep(1000);
Console.WriteLine("Waiter run");
_ready.Set();
}
}
static void Waiter1()
{
for (; ; )
{
_go1.WaitOne();
Thread.Sleep(5000);
Console.WriteLine("water1 run");
_ready1.Set();
}
}
static void Waiter2()
{
for (; ; )
{
_go2.WaitOne();
Thread.Sleep(500);
Console.WriteLine("water2 run");
_ready2.Set();
}
}
}