是否有可能知道哪个线程首先完成?

时间:2014-09-11 13:19:20

标签: c# multithreading

如果我有3个线程。是否可以先知道哪个线程已完成。

一些示例代码

    Thread thread1 = new Thread(() => MyFunc());
    Thread thread2 = new Thread(() => MyFunc());
    Thread thread3 = new Thread(() => MyFunc());

   thread1.Start();
   thread2.Start();
   thread3.Start();

   while (thread1.IsAlive || thread2.IsAlive || thread3.IsAlive)
   {
        //I need condition to which thread dead first.
    }

3 个答案:

答案 0 :(得分:1)

您可以使用Interlocked.CompareExchange设置获胜线程:

static Thread winner = null;

private static void MyFunc()
{
    Thread.Sleep((int)(new Random().NextDouble() * 1000));
    Interlocked.CompareExchange(ref winner, Thread.CurrentThread, null);
}

public static void Main()
{
    Thread thread1 = new Thread(() => MyFunc());
    Thread thread2 = new Thread(() => MyFunc());
    Thread thread3 = new Thread(() => MyFunc());

    thread1.Name = "thread1";
    thread2.Name = "thread2";
    thread3.Name = "thread3";

    thread1.Start();
    thread2.Start();
    thread3.Start();

    thread1.Join();
    thread2.Join();
    thread3.Join();

    Console.WriteLine("The winner is {0}", winner.Name);
}

Live Demo

更新:如果您在检查之前不希望所有主题都完成,则可以使用AutoResetEventWaitHandle.WaitAny()更简单的方法:

private static void MyFunc(AutoResetEvent ev)
{
    Thread.Sleep((int)(new Random().NextDouble() * 1000));
    ev.Set();
}

public static void Main()
{
    AutoResetEvent[] evs = {new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false)};
    Thread thread1 = new Thread(() => MyFunc(evs[0]));
    Thread thread2 = new Thread(() => MyFunc(evs[1]));
    Thread thread3 = new Thread(() => MyFunc(evs[2]));

    thread1.Start();
    thread2.Start();
    thread3.Start();

    int winner = WaitHandle.WaitAny(evs);

    Console.WriteLine("The winner is thread{0}", winner + 1);
}

Live Demo

答案 1 :(得分:0)

一个简单的解决方法是在完成后将线程名称写入列表或其他内容?

答案 2 :(得分:0)

在代码的最后一条指令完成后,所有线程都可以有任意延迟。在最后一条指令运行后,操作系统仍有一些工作要做。这可能需要很长的时间。

因此,找出首先完成的线程是没有意义的。 This is the XY-Problem.这个问题毫无意义。它的答案不会帮助你完成任何事情。问一个关于真正问题的新问题。

您可能想要先了解多个副作用中的哪一个发生。即使它们按顺序A, B完成,它们运行的​​线程也可以按任何顺序完成。线程顺序告诉你什么。