Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wrote this little program:

class Program {     static void Main(string[] args)     {         Thread t = new Thread(WriteX);         t.Start();          for (int i = 0; i < 1000; i++)         {             Console.Write("O");         }     }      private static void WriteX()     {         for (int i = 0; i < 1000; i++)         {             Console.Write(".");         }     } } 

I ran it about fifty times, and the first character on the console was always "O". It is weird for me, because the t thread starts first then the main continues.

Is there any explanation for this?

like image 764
KOB Avatar asked Jun 01 '15 07:06

KOB


People also ask

What is the main thread in C?

In the main thread (i.e. main function; every program has one main thread, in C/C++ this main thread is created automatically by the operating system once the control passes to the main method/function via the kernel) we are calling pthread_cond_signal(&cond1); .

How will you make sure that main thread is the last one to exit?

How to make the main processs ended last? So the sub-thread will wait for each of the threads that it spawned to finish and then it will finish. The main thread will wait for the sub-thread to finish and will then finish last. FYI: it is not a problem to have the main thread finish before the sub-threads.

Is Main a thread or a process?

A process is the first thread started (called the main thread). It's the only thread that is authorized to start a new threads. A process is a unit of resources, while a thread is a unit of: scheduling.


1 Answers

This is probably because Thread.Start first causes the change of state of thread on which it is called and OS schedules it for execution whereas the main thread is already running and does not need these two steps. This is probably the reason that the statement in main thread executes first rather the one in the newly created thread. Keep in mind the sequence of thread execution is not guaranteed.

Thread.Start Method

1) Thread.Start Method Causes the operating system to change the state of the current instance to ThreadState.Running.

2) Once a thread is in the ThreadState.Running state, the operating system can schedule it for execution. The thread begins executing at the first line of the method represented by the ThreadStart

Edit It seems to me that representing this in graphical form will make this more clear and understandable. I tried to show the sequence of thread execution in diagram below.

enter image description here

like image 111
Adil Avatar answered Oct 14 '22 13:10

Adil