multithreading - Why does the main thread's output come first in C#? -


i wrote little program:

class program {     static void main(string[] args)     {         thread t = new thread(writex);         t.start();          (int = 0; < 1000; i++)         {             console.write("o");         }     }      private static void writex()     {         (int = 0; < 1000; i++)         {             console.write(".");         }     } } 

i ran fifty times, , first character on console "o". weird me, because t thread starts first main continues.

is there explanation this?

this because thread.start first causes change of state of thread on called , os schedules execution whereas main thread running , not need these 2 steps. reason statement in main thread executes first rather 1 in newly created thread. keep in mind sequence of thread execution not guaranteed.

thread.start method

1) thread.start method causes operating system change state of current instance threadstate.running.

2) once thread in threadstate.running state, operating system can schedule execution. thread begins executing @ first line of method represented threadstart

edit seems me representing in graphical form make more clear , understandable. tried show sequence of thread execution in diagram below.

enter image description here


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -