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?
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With