• No results found

Multithreading 161 

In document CSharp Handout v1.0 (Page 161-166)

Learning Objectives

After completing this session, you will be able to: ‰ Explain how threading works

‰ Differentiate between threads and processes ‰ Identify when and how to use threads

Multithreading

Multithreading is the ability of the operating system to have at the same point of time multiple threads in memory which switch between the tasks so as to provide a pseudo parallelism, as if all the tasks are running simultaneously. This illusion of concurrency is ensured by the Operating System by providing a specific time slice to each and every thread and then switching between the threads once their slice is over. This switching is very fast. The switching between the threads involves a context switch which in turn involves saving the current thread’s state, flushing the CPU and handling control of the CPU to the next thread in the queue. Remember that at any point of time the CPU can execute only one thread. It is to be noted here that Multiprocessing involves multiple processor with each executing one thread at any particular point of time.

Multithreading can be of the following two types: ‰ Cooperative

‰ Preemptive

In the Cooperative mode of multithreading a thread can have the control of the processor as long as it needs without the need to necessarily preempt them. In order words, in this type of

multithreading the control of the processor lies with the executing thread. In the preemptive mode of operation however, the operating system has control over the processor and decides the time slice for each thread for which it would execute and preempts threads if and when required.

Thread States:

From the Operating System concepts we can classify a thread broadly in one of the following states.

‰ Ready or Runnable state ‰ Running state

‰ Wait state

When a thread is first created it is put in the ready state. A thread in the ready state is one that has all the required resources for it to execute except the processor. It waits in the runnable queue for its turn to come. It would be scheduled from the ready or the runnable state to the running state when its turn comes. However, a thread of a higher priority than another thread would be scheduled prior to the other threads in the ready queue. A thread in the wait state is waiting for its IO to be complete.

A thread is scheduled from the runnable queue to the running state by a module of the operating system known as the scheduler. A thread in the running state has everything including the processor. Remember that at any point of time a single processor can execute only one thread.

How Threading Works:

Multithreading is managed internally by a thread scheduler, a function the CLR typically delegates to the operating system. A thread scheduler ensures all active threads are allocated appropriate execution time, and that threads that are waiting or blocked – for instance – on an exclusive lock, or on user input – do not consume CPU time.

On a single-processor computer, a thread scheduler performs time-slicing – rapidly switching execution between each of the active threads.

On a multi-processor computer, multithreading is implemented with a mixture of time-slicing and genuine concurrency – where different threads run code simultaneously on different CPUs. It's almost certain there will still be some time-slicing, because of the operating system's need to service its own threads – as well as those of other applications.

A thread is said to be preempted when its execution is interrupted due to an external factor such as time-slicing.

The Thread Pool class

Thread Pooling is a concept where the tasks are stored in a queue and the threads are created to handle these tasks. This creation of the threads is taken care of by the Thread Pool itself. Thus thread management is handled by the thread pool. Thread Pooling is enabled by the usage of the Thread Pool class in the System. Threading namespace. It enables us to use the resources efficiently by optimizing thread time slices on the processor. At any point of time there would be one thread pool per process and the maximum limit is 25 indicating that the thread pool can contain, at any point of time, a maximum of 25 worker threads in the pool. The Thread Pool creates the worker threads and assigns each a task from among the pending tasks in the queue.

Multithreading in C#

The C# library has a namespace called System. Threading that provides the functionality of implementing threads in C supported thread states in C#.

In Sun’s Java and Microsoft’s .NET we find that they have modified or enhanced the above states and given some meaningful names to them. The Thread State enum in the System.Threading namespace in C# contains the various supported thread states in .NET. The following are the members of the ThreadState enum.

‰ Unstarted ‰ Running ‰ Background ‰ StopRequested ‰ Suspended

‰ SuspendRequested ‰ WaitSleepJoin ‰ Aborted ‰ AbortRequested ‰ Stopped Thread Priorities:

Based on their importance we can set the priorities of threads. Meaning we can set a thread as having a higher priority than another. Here is an example: suppose there is an application where the application is accepting user input using a thread and another thread is displaying a message to the user indicating the time that has elapsed after the form has be opened. We can set the thread that is responsible for accepting the user input to a higher priority than the other to increase the user responsiveness. This is because the thread with the higher priority would be executed more frequently than one that has a lower priority.

Thread priorities in C# are defined using the ThreadPriority enum. The following are the possible values: ‰ Highest ‰ AboveNormal ‰ Normal ‰ BelowNormal ‰ Normal Creating threads in C#:

The Thread class that belongs to the System.Threading namespace contains the necessary members for creating, suspending, resuming and aborting threads.

Let’s take an example. Consider the following code. using System; using System.Text; using System.Threading; namespace thread { class ThreadTest {

static void Main() {

Thread t = new Thread (new ThreadStart (Go)); t.Start(); // Run Go() on the new thread.

Go(); // Simultaneously run Go() in the main thread. }

static void Go() {

}

} }

When the thread object is first created it is in the unstarted state. The Start () method is responsible for starting the thread. Remember that when we start a thread it might not be immediately started. To be specific, it is actually put in the ready or the runnable state. It is the responsibility of the Operating System to actually schedule the thread from the runnable state to the running state.

Advantages and Disadvantages of Multithreading The following are the major advantages of using Multithreading:

‰ Improved responsiveness ‰ Faster execution

‰ Better CPU and Memory utilization ‰ Support for Concurrency

The following are the drawbacks of using threads:

‰ Problems in testing and debugging due to the non – deterministic nature of execution ‰ Complexity

Summary

‰ A thread is an independent execution path, which is able to run simultaneously with other threads.

‰ Multithreading is managed internally by a thread scheduler, a function the CLR typically delegates to the operating system.

‰ The key difference between threads and processes: o Processes are fully isolated from each other.

o Threads share memory with other threads running in the same application. ‰ To achieve the thread safety, you need to synchronize the threads accessing the

shared memory.

‰ A deadlock is a bug when two threads are trying to access resources, which are locked by each other.

‰ Using threads, you can obtain concurrency, Synchronize memory, and Schedule resources.

Test Your Understanding 1. What is multithreading?

2. What are the different states of thread? 3. How do threading works?

4. What is a Thread Pool class? 5. What is multithreading in C#?

6. What are the possible priority values in Thread priority?? 7. State the advantage of multithreading.

In document CSharp Handout v1.0 (Page 161-166)