Explain the order of thread execution here?

advertisements

From the code below, I though thhat "y" would be printed out before x, but "x" starts printing first. I am reading this in a linear fashion, so why does "x" start printing first even though t.Start() is called first in the main mehod?

static void Main()
{

    Thread t = new Thread(ThreadTest.WriteY);
    t.Start();

    for(int i = 0; i < 1000; i++) Console.Write("x");
}

public class ThreadTest
{
    public static void WriteY()
    {
    for(int i = 0; i < 1000; i++) Console.WriteLine("y");
    }
}


Well, consider it this way.

Give your friend a stack of papers, and keep a stack yourself.

Then you tell your friend "start writing out numbers on those papers", and then immediately you start doing the same.

Now tell me, who of you will finish first?

And, considering this is your question, why?

It is impossible to deterministically type out a correct answer here because there are so many things impacting how fast you two can:

  • start writing out numbers
  • write out numbers
  • move on to the next piece of paper

So basically, your friend might end up starting before you manage to start, or vice versa, but you cannot know beforehand, and it isn't "the right answer".

Every time you run this program, it has the chance of behaving differently, at least in terms of execution order between the two threads.

Having said that, there is overhead involved in spinning up a new thread, which might tip the scale in favor of the main thread entering the loop before the extra thread does. However, I'd be surprised if there is no way that the opposite might happen.