0

我有多个线程在同一个线程安全函数上工作。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()
}
4

2 回答 2

1

这会做到的。只有第一个进入的线程会OnlyFirst从 0 变为 1 并从Interlocked.CompareExchange. 其他线程将失败并从Interlocked.CompareExchangethen接收 1 return

private int OnlyFirst = 0;

private void doWork()
{
    if (Interlocked.CompareExchange(ref OnlyFirst, 1, 0) != 0)
    {
        return;
    }
于 2013-08-31T16:57:49.907 回答
0
// Flag that will only be "true" for the first thread to enter the method.
private bool isFirstThread = true;

// The "Synchronized" option ensures that only one thread can execute the method
// at a time, with the others getting temporarily blocked.
[MethodImplOptions.Synchronized]
private void firstThread()
{
    if (isFirstThread)
    {
        //do some work
        loopCount=0;

        isFirstThread = false;
    }
}
于 2013-08-31T16:56:06.563 回答