Is it possible to know which thread was executed first?
If I have fire 3 streams. Is it possible to know which thread was executed first.
Sample code
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.
}
source to share
You can use Interlocked.CompareExchange
to set the winning stream:
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);
}
UPDATE: . If you don't want all threads to terminate before you check, there is an easier method using AutoResetEvent
and WaitHandle.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);
}
source to share
All threads can have an arbitrary delay after the last instruction of your code completes. After the last instruction has been run, the OS still has some work to do. This can take quite a long time.
For this reason, it never makes sense to figure out which thread was executed first. This is an XY problem. This question doesn't make sense. His answer will not help you achieve anything. Ask a new question with a real problem.
You are probably trying to say which of several side effects occurred first. Even if they terminated in order A, B
, the threads they started can execute in any order. The order of the threads says nothing.
source to share