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?
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.
You say:
"It is weird for me, because the t thread starts first then the main continues.".
This is not true. The "main" tread is already running. When t.Start(); is executed, the OS is told t is in the running state. The OS will then schedule execution time for the thread "soon". This is something else than the OS is instructed to stop execution of this thread until thread t is started. In other words, when Start returns, there is no guarantee that the thread has already started executing.
More of an advice than not an answer:
(Please note, that I see no real-life use for what you are trying to achieve, so I treat your problem as a thought experiment/proof of a concept not explained in detail.)
If you want your threads to "race" for control, don't give your main thread a head start! Creating a thread has some overhead and your main thread is already created (since it creates your other thread). If you are looking for a mostly equal chance for both of your main and worker thread, you should wait for your worker thread to be created in the main thread and wait for the main thread to start the race in your background thread. This can be achived by synch objects.
In practice it would look like this:
You should declare two ManualResetEvents which are visible for both your main- and background thread like this:
private static ManualResetEvent backgroundThreadReady = new ManualResetEvent(false);
private static ManualResetEvent startThreadRace = new ManualResetEvent(false);
Then in your main thread, you should wait for your thread being initialized like:
static void Main(string[] args)
{
Thread t = new Thread(WriteX);
t.Start();
backgroundThreadReady.WaitOne(); // wait for background thread to be ready
startThreadRace.Set(); // signal your background thread to start the race
for (int i = 0; i < 1000; i++)
{
Console.Write("O");
}
}
And in your thread:
private static void WriteX()
{
backgroundThreadReady.Set(); // inform your main thread that this thread is ready for the race
startThreadRace.WaitOne(); // wait 'till the main thread starts the race
for (int i = 0; i < 1000; i++)
{
Console.Write(".");
}
}
Please note that I could have used other waitable sync objects (mutex, autoreset event, even a critical section lock with some hack, I've just choose the simplest, fastest solution which can be extended easily).
Your code is non deterministic. Your code contains no thread primitives that would schedule priority of one thread over another or for one thread to wait for another.
Main process continue its next instructions set after invoking the thread ,It will take time to start thread method as light process.
It basically needs time to start the thread up. You are running the thread code at the same time as the rest of the first method. So taking into account the time it takes to start the thread and then get to the point where it is writing the "." does that make sense?
If you have a sort of reset button in your app to start everything again (without exiting) you may find that the first character is the "." because the thread will already exist.
There is only one reason why the main thread will finish before the created thread and that is because it takes time to start a thread. The only time you would use threads to speed up a program is when 2 tasks can be run at the exact same time. If you want to make the second loop finish first , take a look at Parallel.For loops in c#... these will run each loop in the for loop at the same time (not all of them but as much as your PC can handle)
Related
I have a question of threads that have been bugging me recently. Take a look at this example C# code below.
public void threading()
{
for(int count =0; count< 4; count++)
{
Thread childThread = new Thread(childThread);
childThread.start()
}
return;
}
public void childThread()
{
// Do alot of work
}
As there is a return statement right after the loop within the threading method, would threading execute the return statement before the all the child threads finish executing? I read somewhere that threads are different from forks as they do not create a separate memory region so where would a dead thread end up in?
would threading execute the return statement before the all the child
threads finish executing?
Maybe Yes. Maybe No. It all depends how long your childThread method takes to execute. In case your childThread method is really less time taking then it can happen that all four threads finish before return statement gets executed in threading method.
On the other side if it takes really long time then your threads can continue executing asynchronously even after threading method has finished executing or has returned to Main.
One additional thing you need to know:
By default all these threads they are creating are background threads. So they will exist as long as your process is alive. If your main GUI thread is going to end then these four threads will also go for a toss and will be aborted. So atleast one foreground thread must be alive for your four threads to continue executing childThread method to run to completion.
As far as memory is concerned - Each thread that gets created has its own stack memory area but they share common heap memory. Also, be it stack memory or heap memory of your thread it will certainly be under the periphery of your process's own address space.
If you want to enforce that all child threads terminate before your threading method returns, you can use the Join method on the threads, e.g.
public void Threading()
{
List<Thread> threads = new List<Thread>();
// start all threads
for(int count =0; count< 4; count++)
{
Thread childThread = new Thread(ChildThread);
childThread.start();
threads.Add(thread);
}
// block until all threads have terminated
for(int count =0; count< 4; count++)
{
threads[count].Join();
}
// won't return until all threads have terminated
return;
}
public void ChildThread()
{
// Do alot of work
}
I am exploring threading concept,
Every time when i tried to execute the below code, I am getting different output.
I am starting ThreadOne first, But why is ThreadTwo getting started.
Why am I getting Different output? Can someone explain in Detail?
Thanks In Advance.
static Object newLockobj = new Object();
static void Main(string[] args)
{
Thread tobj1 = new Thread(ThreadOne);
Thread tobj2 = new Thread(ThreadTwo);
tobj1.Start();
tobj2.Start();
Console.ReadLine();
}
static void ThreadOne()
{
Console.WriteLine("Thread One Entered");
lock (newLockobj)
{
Console.WriteLine("Thread 1 started");
Thread.Sleep(2000);
Console.WriteLine("Thread 1 ended");
}
}
static void ThreadTwo()
{
Console.WriteLine("Thread Two Entered");
lock (newLockobj)
{
Console.WriteLine("Thread 2 started");
Thread.Sleep(1000);
Console.WriteLine("Thread 2 ended");
}
}
This is a basic examle for Concurrency. Once you call the .Start() method on a thread object, it starts getting executed independent of the thread that started it. What your programm is doing:
Create the thread objects
Start tobj1 (the thread is not executed directly, but once the scheduler finds a place to put it)
Start tobj2 (the thread is again not executed directly)
The scheduler is responsible to tell the processor which process and which thread to execute. The order in which the threads are started is of no importance.
As soon as one thread starts, he prints the first line ("Thread X Entered"). The Lock is a synchronization statement. Since both threads sync on the same object instance, they cannot enter the Lock block both (Mutual Exclusion). The Lock statement only ensures that the process can work in the critical section without the other process working it his critical section. As you see in your right output, a thread can be interrupted although he is in his critical section ("Thread 2 started", "Thread One Entered", "..."). "Thread One", however, is not allowed to his critical section since the other thread did not release the lock yet.
This is in the heart of threads programming. While you have control over which thread you want to start first, the CPU is not obliged to follow your order of events. During the execution of one thread the CPU is guaranteed to follow you order of code execution as per your programming. When it comes to scheduling different threads, the CPU will follow its own logic and sometimes that logic can seem like random behavior. It will allocate processing time to different threads as it sees fit.
I suggest you read up more on threads programming as not fully understanding this concept and appreciating it's potential pitfalls will lead to many days of hair pulling and possible deadlocks :)
Just google: c# threading. You will get plenty of good resources!
I am creating an application, that is required to do some work in a new thread and save results to static list, then thread dies naturally. There can be only one instance of this additional thread executing at time, so when function responsible for creating thread find thread already working, it should return.
When creating my appliaction i was using this guide on msdn: http://msdn.microsoft.com/en-us/library/7a2f3ay4%28v=vs.80%29.aspx
This guide says:
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
// Loop until worker thread activates.
while (!workerThread.IsAlive);
// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);
So i used this code in my app:
if (TibiaControl.PathFinder.PathFinderThread != null && TibiaControl.PathFinder.PathFinderThread.IsAlive)
return false;
TibiaControl.PathFinder Finder = new TibiaControl.PathFinder(targetX, targetY);
TibiaControl.PathFinder.PathFinderThread = new Thread(new ThreadStart(Finder.FindPath));
TibiaControl.PathFinder.PathFinderThread.Start();
SystemControl.DebugMessage(0, "_findPath -- 1");
while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;
Thread.Sleep(1);
SystemControl.DebugMessage(0, "_findPath -- 2");
But when executing this function with high frequency (like once every 20-30ms) it happens that my app gets stuck on
while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;
line and main thread gets stuck in an infinite loop (as if thread already have it's work done before an while loop occurs). How can I fix that?
I think you may have blindly copied some code from the example that you don't need:
while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;
Thread.Sleep(1);
The reason they did this was to demonstrate the usefulness of their RequestStop method.
I wouldn't use that code as the source for any useful application. First of all, there's much better ways for threads to wait. For example, ManualResetEventSlim. Second, it's hard to tell from the code you've posted whether IsAlive is volatile. Even, then, in an x86 system that really doesn't do anything w.r.t. special code. I would recommend using a safer and more explicit form of thread safe value reading. For example:
while (0 == Interlocked.Read(ref workerThread.IsAlive));
Which means changing creating a new variable IsAlive to as a long. But then, in a single CPU system you've just made the one and only CPU busy with little chance of other threads getting a chance to use it. You should yield control to other threads:
while (0 == Interlocked.Read(ref workerThread.IsAlive)) Thread.Sleep(1);
But, I think starting with that sample code is a bad idea. Try to figure out what you need to do and detail that...
For more information see http://msdn.microsoft.com/en-us/magazine/jj863136.aspx and http://msdn.microsoft.com/en-us/magazine/jj883956.aspx
Combine the IsAlive loop with querying the ThreadState:
while (!myThread.IsAlive
&& myThread.ThreadState != ThreadState.Stopped
&& myThread.ThreadState != ThreadState.Aborted)
{}
This avoids endless loops for the case the thread stops immediately after starting
using System;
using System.Threading;
// Simple threading scenario: Start a static method running
// on a second thread.
public class ThreadExample {
// The ThreadProc method is called when the thread starts.
// It loops ten times, writing to the console and yielding
// the rest of its time slice each time, and then ends.
public static void ThreadProc() {
for (int i = 0; i < 10; i++) {
Console.WriteLine("ThreadProc: {0}", i);
// Yield the rest of the time slice.
Thread.Sleep(0);
}
}
public static void Main() {
Console.WriteLine("Main thread: Start a second thread.");
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. C# simplifies the creation of this delegate.
Thread t = new Thread(new ThreadStart(ThreadProc));
// Start ThreadProc. Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields. Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
t.Start();
//Thread.Sleep(0);
for (int i = 0; i < 4; i++) {
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(0);
}
Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
t.Join();
Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program.");
Console.ReadLine();
}
}
The result is :
Main thread: Start a second thread.
Main thread: Do some work.
ThreadProc: 0
Main thread: Do some work.
ThreadProc: 1
Main thread: Do some work.
ThreadProc: 2
Main thread: Do some work.
ThreadProc: 3
Main thread: Call Join(), to wait until ThreadProc ends.
ThreadProc: 4
ThreadProc: 5
ThreadProc: 6
ThreadProc: 7
ThreadProc: 8
ThreadProc: 9
Main thread: ThreadProc.Join has returned. Press Enter to end program.
I don't understand why "ThreadProc 0" "1" "2" "3" can appear in between " Main thread: Do some work."
Can anybody help me explain it? thanks!
The "t.Start()" line starts the other thread which is running simultaneously while the main thread is doing it's work.
I think it would help you to read up about threads in general in computer science.
A thread (in my words) is an asynchronous unit of work. Your processor hops between different threads in your program to complete work at different intervals. The benefit you get is being able to perform work on one thread while another is waiting for something (like Thread.Sleep(0)). You also can utilize multiple core CPUs, since one core can execute one thread the same time as another.
Does that explain some?
The idea is that each thread is like a mini-process contained within the process of your program. The operating system then divides up the CPU execution time amongst them.
The calls to Sleep hasten the switching from one thread to the next. Without them, you might not see the intertwined output, but then again you might - the point is it's not really up to you when you make multiple threads which one executes and when - that's why you have to assume any thread might execute at any time and leads you into the concepts of locking and synchronization (which I'm sure you'll run into next or soon).
This seems correct. As soon as you start ThreadProc
t.Start();
it runs at the same time as main thread. So the System will print whichever print statement happens first. You will get the statements merged because both loops go at the same time.
MSDN saying that Thread.Start() method
Causes the operating system to change the state of the current
instance to ThreadState.Running.
Once a thread is in the ThreadState.Running state, the operating
system can schedule it for execution.
Output you've provided clearly shows that OS ran thread immediately and then switches control between both threads, try out
t.Priority = ThreadPriority.Lowest;
t.Start();
and see whether execution order has changed
I would like to invoke heavy duty method dowork on a separate thread and kill it if its taking longer than 3 seconds. Is there any problem with the following code?
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("starting new thread");
Thread t = new Thread(new ThreadStart(dowork));
t.Start();
DateTime start = DateTime.Now;
TimeSpan span = DateTime.Now.Subtract(start);
bool wait = true;
while (wait == true)
{
if (span.Seconds > 3)
{
t.Abort();
wait = false;
}
span = DateTime.Now.Subtract(start);
}
Console.WriteLine("ending new thread after seconds = {0}", span.Seconds);
Console.WriteLine("all done");
Console.ReadLine();
}
static void dowork()
{
Console.WriteLine("doing heavy work inside hello");
Thread.Sleep(7000);
Console.WriteLine("*** finished**** doing heavy work inside hello");
}
}
This is a very bad programming practice. Do not start up threads that you cannot shut down cleanly. The code which starts the thread and the code which runs the thread should have some well-defined mechanism by which they can communicate. There are many such mechanisms; for example, the worker thread could periodically ask the owner thread "should I keep going?" The worker thread could periodically check a threadsafe field that says whether to halt soon. And so on.
If you are starting up work on a new thread and you do not know what it is doing or how long it is going to take, then you are playing with fire. Particularly if that thread code could be hostile and actively resisting being taken down. There is no guarantee whatsoever that aborting a thread does anything at all; if you are clever then you can write code that makes threads that are resistant to thread aborts.
If you're in that situation, the right thing to do is to start up the code in a new process, not a new thread, and then shut down the process when it takes too long.
If it were me, I'd use the Thread.Join() overload that takes a milliseconds parameter. (Or the one that takes a TimeSpan.) It's cleaner and involves fewer lines of code.
t.Start();
if (!t.Join(3000))
t.Abort();
Or, like Matti said, put the timing logic inside threaded process and have it self-destruct.
I think you need to learn about Thread.Join(int). It will attempt to join with a thread and after a specified timeout it'll exit, upon which you can call Thread.Abort().