首页 文章

C#我需要允许第一个线程到达certian点以防止其他线程继续

提问于
浏览
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()
}

2 回答

  • 0

    这样做 . 只有第一个要输入的线程会将 OnlyFirst 从0更改为1,并从 Interlocked.CompareExchange 接收0 . 其他线程将失败并从 Interlocked.CompareExchange 然后 return 收到1 .

    private int OnlyFirst = 0;
    
    private void doWork()
    {
        if (Interlocked.CompareExchange(ref OnlyFirst, 1, 0) != 0)
        {
            return;
        }
    
  • 1
    // 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;
        }
    }
    

相关问题