i came across an interview question which required me to simulate a car race .
this was no problem in general , all i did is call the car.Race() method which i built
which loops until it the car reaches its destination ( this is not important !)
what was tricky is to make all 10 threads which the car “raced” on (thread per car )call Car.Race()
simultaneously and not one after the other
Action<Car,ManualResetEvent> raceDel = (car,handel) =>{
handel.WaitOne();
car.Race();
}
main()
{
ManualResetEvent [] handels = new ManualResetEvent[num_cars];
Car [] cars = new Car[num_cars];
for(int i = 0 ; i < num_cars ; i++)
{
handels[i] = new ManualResetEvent(false);
cars[i] = new Car();
raceDel.BeginInvoke(cars[i],handels[i],null,null);
}
// the question lies here , i'm looking for something along the lines of
WaitHandel.SetAll(handels); // which no such method exists :)
}
thread one could start and the car would reach the end of the course before thread 5 even started its execution .
what i did was send a manualresetevent into each thread and called waitOne() on it
the problem now was with what element in the framework could i signal an entire array of ManualResetEvent simultaneously .
WaitHandle has a method WaitHandle.WaitAll(MRE_Array) which would wait for an array of MRE
to call send , i’m looking for something like the opposite which would invoke Set() on an entire array of manualresetevent .
any ideas ?
any work arounds or other synchronization objects that might do the trick would also be well received
thanks in advance
eran.
You just need one
ManualResetEvent.Pass it to all your threads and they can all wait on the same event.
When the Wait Handle is signalled, all blocked threads are allowed to continue.
This does not mean they will all continue execution concurrently – that’s up to the OS scheduler – but in practice it will be close, given enough physical cores.