我有多线程处理相同的线程安全功能 . 经过X次迭代后,第一个到达firstThread()的线程将执行firstThread()并阻止其他线程继续,直到线程完成firstThread() . 只有第一个到达firstThread()的线程才会执行其他线程 . 有点像第一个到终点线的比赛是赢家 . firstThread()完成后,所有线程都会继续,直到再次达到限制 . 有没有人有任何想法,一个最好的方法来实现这一点,将不胜感激 .
private void ThreadBrain()
{
Thread[] tList = new Thread[ThreadCount];
sw.Start();
for (int i = 0; i < tList.Length; i++)
{
tList[i] = new Thread(ThProc);
tList[i].Start();
}
foreach (Thread t in tList)
if (t != null) t.Join();
}
private void ThProc()
{
doWork();
}
private void firstThread()
{
//do some work
loopCount=0;
}
private void doWork()
{
//do some work
loopCount++;
//first thread to reach this point calls firstThread() and prevent other threads from continuing until current thread completes firstThread()
If(loopCount>=loopLimit)firstThread()
}
2 回答
这样做 . 只有第一个要输入的线程会将
OnlyFirst
从0更改为1,并从Interlocked.CompareExchange
接收0 . 其他线程将失败并从Interlocked.CompareExchange
然后return
收到1 .