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
Related
I have some very simple code that's attempting to multi-thread an existing script.
On inspecting the treads window in visual Studio and calling Thread.CurrentThread.ManagedThreadId it always reports back as the same thread as starting the process. When ending it reports back a different thread id.
The threads do seem to be performing the task asynchronously, but the logging and output from visual studio are making me think otherwise.
Please could someone clarify what is going on and if I've made a mistake in my approach?
namespace ResolveGoogleURLs
{
class Program
{
public static void Main(string[] args)
{
HomeController oHC = new HomeController();
}
}
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ResolveGoogleURLs
{
class HomeController
{
public static int MaxJobs = 5;
public static int RecordsPerJob = 1000;
public static List<Task> TaskList = new List<Task>(MaxJobs);
public HomeController()
{
CreateJobs();
MonitorTasks();
}
public void MonitorTasks()
{
while (1 == 1)
{
Task.WaitAny(TaskList.ToArray());
TaskList.RemoveAll(x => x.IsCompleted);
Console.WriteLine("Task complete! Launching new...");
CreateJobs();
}
}
public async Task CreateJob()
{
Console.WriteLine("Thread {0} - Start", Thread.CurrentThread.ManagedThreadId);
// read in results from sql
await Task.Delay(10000);
Console.WriteLine("Thread {0} - End", Thread.CurrentThread.ManagedThreadId);
}
public void CreateJobs()
{
while (TaskList.Count < MaxJobs)
{
TaskList.Add( CreateJob() );
}
}
}
}
Output:
> Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 4 - End
Thread 5 - End
Thread 4 - End
Thread 6 - End
Thread 8 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 7 - End
Thread 6 - End
Thread 5 - End
Thread 4 - End
Thread 8 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 10 - End
Thread 9 - End
Task complete! Launching new...
Thread 1 - Start
Thread 7 - End
Thread 4 - End
Thread 6 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Tasks (class Task) are not the same as threads (class Thread).
Thread can be imagined as a virtual CPU that can run its code in same time than other threads. Every thread has its own stack (where local variables and function parameters are stored). In .NET a thread is mapped into a native thread - supported by the platform (operation system), that has things like thread kernel object, kernel mode stack, thread execution block, etc.. This makes thread a pretty heavy-weight object. Creation of new thread is time consuming and even when threads sleeps (doesn't execute its code), it still consumes a lot of memory (thread stack).
The operation system periodically goes through all running threads and based on their priority it assigns them a time slot, when a thread can use the real CPU (execute its code).
Because threads consume memory, they are slow to create and running too many threads hurts overall system performance, tasks (thread pools) were invented.
Task internally uses threads, because threads are the only way how to run code in parallel way in .NET. (Actually it's the only way how to run any code.) But it does it in efficient way.
When a .NET process is started, internally it creates a thread pool - a pool of threads that are used to execute tasks.
Task library is implemented in that way that when a process is started, a thread pool contains only a single thread. If you start to create new tasks, they are stored into a queue from which that single thread takes and execute one task after another. But .NET monitors if that thread is not overloaded with too many tasks - situation when tasks are waiting 'too long' in a thread pool queue. If - based on its internal criteria - it detects that initially created thread is overloaded, it creates a new one. So thread pool now has 2 threads and tasks can be ran on 2 of them in parallel way. This process can be repeated, so if a heavy load is present, thread pool can have 3, 4 or more threads.
On the other hand, if the frequency of new tasks drops down, and thread pool threads don't have tasks to execute, after 'some time' (what is 'some time' is defined by internal thread pool criteria) thread pool can decide to release some of threads - to conserve system resources. Number of thread pool threads can drop down to initially created single thread.
So task library internally uses threads, but it tries to use them in efficient way. Number of threads is scaled up and down based on the number of tasks program wants to execute.
In almost all cases tasks should be preferred solution to using 'raw' threads.
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)
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C#: Waiting for all threads to complete
I have a console app that spawns some threads and then exits. Each thread takes roughly ~20 seconds to complete. It appears as though the console app is spawning the threads and then exiting before the threads have a chance to complete.
How do I tell the console app not to exit until all threads it has spawned have completed?
You can to use a CountDownEvent.
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static CountdownEvent countdown;
static void Main(string[] args)
{
countdown = new CountdownEvent(1);
for (int i = 1; i < 5; i++)
{
countdown.AddCount(); //add a count for each (BEFORE starting thread .. Thanks, Brian!)
//do stuff to start background thread
}
countdown.Signal(); //subtract your initial count
countdown.Wait(); //wait until countdown reaches zero
//done!
}
static void backgroundwork()
{
//work
countdown.Signal(); //signal this thread's completion (subtract one from count)
}
}
}
Are the threads spawned for a loop? If so a Parallel.ForEach would work:
ParallelOptions options = new ParallelOptions();
Parallel.ForEach(items, options, item=>
{
// Do Work here
});
As long as the Thread is not a background-thread (.IsBackground), the app should stay alive:
static void Main()
{
Thread thread = new Thread(MoreStuff);
thread.IsBackground = false;
thread.Start();
Console.WriteLine("Main thread exiting");
}
static void MoreStuff()
{
Console.WriteLine("Second thread starting");
Thread.Sleep(5000); // simulate work
Console.WriteLine("Second thread exiting");
}
Nothing else is needed. Note that the ThreadPool will use background threads; is the problem perhaps that you are using ThreadPool here?
Note: if the second thread hasn't actually started there might be a small race where it can exit prematurely; you might want to gate the threads starting.
You can use Thread.Join to wait for a thread to complete.
How are you launching the threads? It really depends, but if you are just using the Thread class, then call yourThread[i].Join() from the main thread to ensure that all threads complete.
Look into the Tasks and Task Factory to handle things a lot more cleanly than in years past.
Call Thread.Join() on all of the Threads that you start after they have started. This will block the current thread until the thread is complete.
You should probably use synchronization and wait for any spawned threads to complete their work, either by blocking the main thread with calls to Thread.Join or using signalling (e.g. using a Monitor or one of the other options for this).
Alternatively you can simply make the spawned threads run as foreground threads, by setting the IsForeground property (afaicr). This will keep the application alive until the threads have terminated, but you will still see the console window disappear as the main thread exits.