Friday, 27 December 2013

Multi-threading or threading (part 3)

In this post we are going to look at the interaction between the main thread and artificial threads (i.e. Threads created by the main thread). In one of our last posts,  we discuss how threads interact by sharing state.

One of the most common example is Thread.Sleep(/* sleep time */). Whenever this static method is called,  its pauses the currently executing thread and halts its execution. Its time slice is then reassigned by the processor to higher priority threads. It leads to CPU starvation for lower priority threads if used excessively This method is casually used to simulate long running process.

Another  closely related method is Thread.Yield().  This method causes the operating system to yield its time slice to the next thread that is ready to execute in the same processor. This method does not care whether the thread that is scheduled to execute has a higher or lower priority. When a thread yields its execution time, it does so with the assumption that another thread is ready for execution but if that is not the case, the OS will called up the thread that yielded to continue execution.

In one of our last post I mentioned that a thread can be made to run in the foreground or in the background. Supposing that a thread has been set to run as a background thread, the main thread can wait for this thread to finish its execution by calling Thread.Join(/* time to wait  for the background thread). When this method is called, the main thread or the foreground thread will then block and wait for the background thread to finish its code execution. When the background does not finish within this allotted time. The calling thread will then continue on its merry way but on the other hand, if the background thread  has finished execution before this method is called, the calling thread will continue on its merry way.

No comments:

Post a Comment