era*_*zap 2 c# multithreading synchronization
我遇到了一个面试问题,要求我模拟一场赛车比赛.
这一般都没有问题,我所做的只是调用car.Race()方法,我建立的循环直到汽车到达目的地(这不重要!)
什么是棘手的是使汽车"竞赛"的所有10个线程(每辆车的线程)同时调用Car.Race()而不是一个接一个地调用
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 :)
}
Run Code Online (Sandbox Code Playgroud)
线程1可以启动,并且在线程5开始执行之前汽车将到达课程的结尾.
我所做的是向每个线程发送一个manualresetevent并在其上调用waitOne()现在的问题是框架中的哪个元素可以同时发出整个ManualResetEvent数组.
WaitHandle有一个方法WaitHandle.WaitAll(MRE_Array),它会等待一个MRE数组来调用send,我正在寻找相反的东西,它会在整个manualresetevent数组上调用Set().
有任何想法吗 ?
感谢提前eran,任何可以解决问题的工作或其他同步对象也会很受欢迎.
你只需要一个ManualResetEvent.
将它传递给你所有的线程,他们都可以等待同一个事件.
当发出等待句柄信号时,允许所有被阻止的线程继续.
这并不意味着它们将同时继续执行 - 这取决于操作系统调度程序 - 但实际上,如果有足够的物理内核,它将会很接近.
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |