Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have created a basic thread program to understand how threads work.
however the result that i am getting is not what i expected [ like i knew what the result will be .. lol :p]
here is the code

class Program
    {
        public Thread myThread;
        string myName;

        public Program( string name)
        {
            myName = name;
            myThread = new Thread(new ThreadStart(WorkerMethod));
        }

        private void WorkerMethod()
        {
            Console.WriteLine("Hello , ");
            Thread.Sleep(1500);
            Console.WriteLine(myName);
        }
        static void Main(string[] args)
        {
           

            Program objProg1 = new Program("James");
            Program objProg2 = new Program("Bond");
            objProg1.myThread.Start();
            objProg2.myThread.Start();
            Console.ReadLine();
        }

       
    }


Tell me that what i am understand is wrong.
In the main thread of ObjProg1 starts , after that thread of ObjProg2 starts.
so i think first Hello for ObjProg1 is called then thread goes to sleep and execution passes on to ObjProg2 here Hello is called again and the thread goes to sleep now the execution returns to objProg1 and James should be printed and after that Bond .

so result according to my Understanding [or Misunderstanding] should be like
Hello,
Hello,
James
Bond

but the result that i am seeing is
Hello,
Hello,
Bond
James

Alert !!!

Now that i have re run the application the result is as i was expecting it.
so basically what's happening is that result is different everytime.

Please help me understand how it is working and why the results are different everytime.
Posted
Updated 22-Sep-15 8:11am
v2

This happens because you can't guarantee which order the thread are going to execute in. Windows schedules threads to run whenever it needs them to, not when you think they are going to execute.

You're thinking of your threads in your application as the only ones running in the system. Fact is your threads are just 3 in a sea of them. Open Task Manager, select View, Select columns.... Turn on the Threads column and see how many threads are running in the system at the same time your app is running. On my machine, right now, there's about 1,400 threads running.

Threads run whenever they get a chance to, not necessarily in the order you launched them.
 
Share this answer
 
Comments
Riya-Pandey 22-Sep-15 14:27pm    
So basically what you are saying is that we can't have a sequence in which the thread will run ??
what if i have a situation where i need thread1 to be executed before thread2 ? how will i handle that case ?
Dave Kreskowiak 22-Sep-15 17:07pm    
I'd probably use Tasks for that instead of directly creating thread. Tasks offer the control you're asking about and are run on threads in the managed Thread Pool.

https://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx
Your "error" in thinking is, that you assume that the threads start synchronously in the order you create your program classes.
In fact you only "delegate" to the system, that you want to start a thread, and immediately a second thread.
There is simply no guarantee that the first thread will be up and running before the second thread if you do it this way.

There are lots of ways to synchronize that.

For this small demo, I show you a secret :)
A Thread has a "ThreadState" property where you can see, if it is running.

So, if you just put that little while... between your two thread starts, you force the program to wait until the first thread is in running state, before the second thread gets started.
Then you will always have the hello,hello,james bond output.

C#
Program objProg1 = new Program("James");
				Program objProg2 = new Program("Bond");
				objProg1.myThread.Start();
				while (objProg1.myThread.ThreadState != ThreadState.Running) ;
				objProg2.myThread.Start();
				Console.ReadLine();


Kind regards, Mike
 
Share this answer
 
Comments
Riya-Pandey 22-Sep-15 14:33pm    
The order here is still unexpected. well from the solutions posted i get that we can't know the order in which windows will execute a thread.
Why would you assume any specific order of execution in two threads of the same priority? Windows is a preemptive multitasking system, so it can start and stop threads at any point in their execution, and allow any other thread or task to take over, provided it isn't "Blocked" or waiting for something specific to happen.

Depending on the load on your system, and the number of cores available, you aren't even guaranteed to get the whole word "Hello," printed before the thread execution is stopped and the second thread starts. So it's quite possible that at some point you could get
HHeelllloo,,

JBonamd
es
instead of the output you expect.

Threads are a difficult concept, and it's very difficult to "work out what is happening" from trivial examples, because they don't last long enough to really demonstrate what is going on.

What I'd suggest is that you try using a BackgroundWorker instead of a "naked" thread as they make it easier to do some things - for example they have progress reporting built in - and use longer running tasks which report via progress to your main thread.
Try having one thread looking at all the files in a folder (and it's subdirectories) and issuing a "progress" for each file name it finds. And another working out something more CPU intensive like a Fibonacci sequence and reporting that back via progress events.
The progress events will queue in the "main" thread which then prints them one by one and you should see that the output is not consistent from run to run, but that the three threads work completely independently.
 
Share this answer
 
Comments
Riya-Pandey 22-Sep-15 14:42pm    
Yeah it really is a difficult concept. God!!!, what will happen when i try to understand multi threading. really scary stuff.
You suggested using a background Worker Process. like main method?
OriginalGriff 22-Sep-15 14:48pm    
No, a BackgroundWorker - it's a class:
https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
And it's designed to "report back" to a different task as to how it's doing (so you can provide the user with updates while you load a lot of information, or download a big file, or whatever).
That reporting is easy to use, and better illustrates what is going on when you have multiple "Other threads" running together.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900