Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 38 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
38
Dung lượng
0,9 MB
Nội dung
Creating Multithreaded Applications Chapter 11 A program executes as a single, sequential flow of control. A program can also be designed to execute multiple tasks. To execute multiple tasks in your program, you can use threads. This chapter discusses implementation of threads and their life cycle. The chapter also discusses implementing multiple threads and prioritizing threads. In addition, this chapter discusses thread synchronization and communication between processes. In this chapter, you will learn to: Implement threads Define the life cycle of a thread Implement multiple threads Identify the thread priority Use synchronization in threads Identify communication between processes Objectives ¤NIIT Creating Multithreaded Applications 11.3 A thread is defined as the execution path of a program. You can define a unique flow of a control in a program, using a thread. Threads are used to run applications that perform large and complex computations. For example, a Central Processing Unit (CPU) performs various complex tasks simultaneously. The processes include tasks such as writing and printing a document, installing software, and displaying the date and time on the status bar. All these processes are handled by separate threads. A process that is executed using one thread is known as a single-threaded process, where the process is a running instance of a program. A single-threaded application can perform only one task at a time. You have to wait for one task to complete before another task can start. The following figure shows a single-threaded process. A Single-Threaded Process To execute more than one task at a time, you can create multiple threads in a program. A process that creates two or more threads is called a multithreaded process. For example, any Web browser, such as Internet Explorer is a multithreaded application. Within the browser, you can print a page in the background while you scroll the page. Similarly, you can play audio files and watch animated images at the same time. Each thread in a multithreaded process runs at the same time and maintains a different execution flow. The following figure shows a multithreaded process with two threads. A Multithreaded Process Implementing Threads 11.4 Creating Multithreaded Applications ¤NIIT The Thread Model A program uses threads to increase the efficiency of a CPU by preventing wastage of the CPU cycles. In single-threaded systems, an approach called event loop with polling is used. Polling is the process in which a single event is executed at a time. In the event loop with polling approach, a single thread runs in an infinite loop till its operation is completed. When the operation is completed, the event loop dispatches control to the appropriate event-handler. No more processing can happen in the system until the event-handler returns. This results in the wastage of the CPU time. In a single-threaded application if the thread is suspended from execution because it is waiting for a system resource, the entire program stops executing. This limitation can be overcome by using multithreading, which eliminates the event loop with polling approach. In multithreading, the time for which a thread waits for the CPU time can be utilized to perform another task. In C#, you will use the Thread class to work with threads. The System.Threading.Thread class is used to construct and access individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread. The Main Thread The main thread is created automatically on the start up of a C# program execution. The threads which are created exclusively using the Thread class are called as child threads, where the main thread is either called a parent thread or a primary thread. You can access a thread using the CurrentThread property of the Thread class. The following code shows the execution of main thread using its CurrentThread property in the Thread class: using System; using System.Threading; namespace ThreadExample { class MainThreadExample { public static void Main(string[] args) { Thread Th = Thread.CurrentThread; Th.Name = "MainThread"; Console.WriteLine("The current thread after name change :{0}", Th.Name); Console.ReadLine(); ¤NIIT Creating Multithreaded Applications 11.5 } } } The output of the preceding code is as follows. Output of the Main Thread Program In the preceding code, a reference to the current thread is obtained by using the CurrentThread parameter of the Thread class and its reference is stored in the Th variable. The Name parameter is used to set the name of the thread, and the information about the thread is displayed. In C#, you create a thread by creating an object of type Thread, giving its constructor a ThreadStart reference, and calling the new thread’s Start() method. The new thread starts executing asynchronously with an invocation of the thread’s method. When the method returns, the thread dies. The other methods of the Thread class allow managing the lifetime of the thread and destroying the thread when required. There are various methods available with the Thread class. Using these methods, you can control the execution of threads. Few of these methods are: Start(): Starts a thread Sleep(): Makes the thread to pause for a period of time W orking with Threads 11.6 Creating Multithreaded Applications ¤NIIT Abort() : Terminates the thread Suspend(): Suspends a thread. If the thread is already suspended it has no effect Resume(): Resumes the suspended thread Working with threads involves creating, managing, and destroying threads. Creating Threads You can create threads by extending the Thread class. The extended Thread class calls the Start() method to begin the child thread execution. You can use the following code to create a thread by extending the Thread class: using System; using System.Threading; namespace ThreadSample { class BasicThreadApp { public static void ChildThreadCall() { Console.WriteLine("Child thread started"); } public static void Main() { ThreadStart ChildRef = new ThreadStart(ChildThreadCall); Console.WriteLine("Main - Creating Child thread"); Thread ChildThread = new Thread(ChildRef); ChildThread.Start(); Console.WriteLine("Main - Have requested the start of child thread"); Console.ReadLine(); } } } ¤NIIT Creating Multithreaded Applications 11.7 The output of the preceding code is as follows. Output of the Create Thread Program In the preceding output, the Main() method prints before the message from the child thread, proving that the child thread is indeed working asynchronously. The first statement in the preceding code is the using statement for the System.Threading namespace. The first statement of the Main() method specifies the method to be invoked by the thread: ThreadStart ChileRef = new ThreadStart(ChildThreadCall); The next statement instantiates a Thread object where the constructor takes the object of the ThreadStart class as its argument: Thread ChildThreads = new Thread(ChildRef); Then, the Start() method of the Thread object is called, and the method results in a call to the ChildThreadCall method. The extended Thread class calls the Start() method to begin the child thread execution. Managing Threads There are many tasks you might need to perform to manage the activity or life of a thread. You can manage all these tasks by using the various thread methods available with the Thread class. 11.8 Creating Multithreaded Applications ¤NIIT For example, when you require the thread to pause for a period of time so that the thread is allowed to execute, you can call the Thread.Sleep() method. This method takes a single argument that represents time in milliseconds for which you want the thread to pause. This method is a static method and cannot be called with an instance of a thread object. This is done to avoid a call to the Thread.Sleep() method on any other thread except the currently executing method. The static Thread.Sleep() method calls the static CurrentThread method, which then pauses that thread for the specified amount of time. The following code shows the implementation of the Sleep() method: using System; using System.Threading; namespace ThreadSample { class BasicThreadApp { public static void ChildThreadCall() { Console.WriteLine("Child thread started"); int SleepTime = 5000; Console.WriteLine("Sleeping for {0} seconds", SleepTime/1000); Thread.Sleep(SleepTime); //Sleep for five seconds. Console.WriteLine("Waking Up"); } public static void Main() { ThreadStart ChildRef = new ThreadStart(ChildThreadCall); Console.WriteLine("Main - Creating Child thread"); Thread ChildThread = new Thread(ChildRef); ChildThread.Start(); Console.WriteLine ("Main - Have requested the start of child thread"); Console.ReadLine(); } } } ¤NIIT Creating Multithreaded Applications 11.9 The output of the preceding code is as follows. Output of the Managing Threads Program There is more than one way to call the Sleep() method. One way is to call Thread.Sleep() with a value 0, which will cause the current thread to hand over the unused balance of its timeslice. The other way is to call Thread.sleep() method with a value of Timeout.Infinite, which results in the thread being paused indefinitely until it is interrupted by another thread calling the suspended thread’s Thread.Interrupt() method. There is another method Thread.Suspend(), which is used to suspend the execution of a thread. The Thread.Suspend() method can be called on the currently executing thread or another thread. When a thread is suspended in this fashion, only another thread can cause its resumption, with the Thread.Resume() method. Notice, when a thread suspends another thread, the first thread is not blocked. The call returns immediately. In addition, regardless of how many times the Thread.Suspend() method is called for a given thread, a single call to Thread.Resume() will cause the thread to resume execution. Destroying Threads If the thread is required to be destroyed, the Thread.Abort() method will allow you to accomplish the task. The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught. If the finally block is present in the method, the runtime will send the control to it. 11.10 Creating Multithreaded Applications ¤NIIT You can use the following code to destroy threads: using System; using System.Threading; namespace ThreadSample { class BasicThreadApp { public static void ChildThreadCall() { try { Console.WriteLine("Child thread started"); Console.WriteLine ("Child thread - counting to 10"); for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.Write("{0} ", i); } Console.WriteLine("Child thread finished"); } catch (ThreadAbortException e) { Console.WriteLine("Exception"); } finally { Console.WriteLine ("Child thread -Unable to catch the exception."); } } public static void Main() { ThreadStart ChildRef = new ThreadStart(ChildThreadCall); Console.WriteLine("Main - Creating Child thread"); Thread ChildThread = new Thread(ChildRef); ChildThread.Start(); //Give the Child thread time to start. Console.WriteLine("Main - Sleeping for 2 seconds"); Thread.Sleep(2000); Console.WriteLine("\nMain - Aborting Child thread"); ChildThread.Abort(); Console.ReadLine(); } } } [...]... access to multiple applications: Provides access to multiple applications at the same time because of quick context switching among threads Program structure simplification: Simplifies the structure of complex applications, such as multimedia applications Each activity can be written in separate methods that makes complex program easy to design and code NIIT Creating Multithreaded Applications 11.21... called inter-process communication The application domain is a logical process inside a physical process The main purpose of the application domain is to isolate your applications from the other applications 11.36 Creating Multithreaded Applications NIIT ... Child1 = new ThreadStart(ChildThread1); ThreadStart Child2= new ThreadStart(ChildThread2); Console.WriteLine("Main - Creating Child threads"); Thread Thread1 = new Thread(Child1); Thread Thread2 = new Thread(Child2); Thread1.Start(); Thread2.Start(); } NIIT } Creating Multithreaded Applications 11.23 Identifying the Thread Priority One of the attributes that controls the behavior of a thread is its... done } Console.Write("{0}", T); } } Console.WriteLine("Child thread 2 finished"); public static void Main() NIIT Creating Multithreaded Applications 11.25 { ThreadStart Child1 = new ThreadStart(ChildThread1); ThreadStart Child2 = new ThreadStart(ChildThread2); Console.WriteLine("Main - Creating Child threads"); Thread Thread1 = new Thread(Child1); Thread Thread2 = new Thread(Child2); Thread1.Priority... In NET, this algorithm is based on the priority level used with the Thread.Priority property, as well as the process’s priority class in the preceding code 11.26 Creating Multithreaded Applications NIIT Using Synchronization in Threads In a multithreaded application, when threads need to share data with each other, the application should ensure that one thread does not change the data used by the other... Fd.WriteData("T2"); Console.WriteLine("Child thread #2 - Returned from Output"); } public static void Main() NIIT Creating Multithreaded Applications 11.29 { ThreadStart Child1 = new ThreadStart(ChildThread1); ThreadStart Child2 = new ThreadStart(ChildThread2); Console.WriteLine("Main - Creating Child threads"); Thread Thread1 = new Thread(Child1); Thread Thread2 = new Thread(Child2); } } Thread1.Start();... FileAccess.WriteData "); Fd.WriteData("T2"); } NIIT Console.WriteLine("Child thread #2 - Returned from Output"); Creating Multithreaded Applications 11.31 public static void Main() { ThreadStart Child1 = new ThreadStart(ChildThread1); ThreadStart Child2 = new ThreadStart(ChildThread2); Console.WriteLine("Main - Creating Child threads"); Thread Thread1 = new Thread(Child1); Thread Thread2 = new Thread(Child2); }... use the System.AppDomain class to manage application domains The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown 11.34 Creating Multithreaded Applications NIIT Practice Questions 1 Which of the following is true about the 'not runnable' state of a thread? a A... animThread.Sleep(2000); c animThread.Resume(); d animThread.Start(); NIIT Creating Multithreaded Applications 11.35 Summary In this chapter, you learned that: A thread is defined as the path of execution of a program It is a sequence of instructions that is executed to define a unique flow of control A program that creates two or more threads is called a multithreaded program The types of multitasking are: Process-based... the program executed The following window verifies the output of the executed program Output of the Hangman Game 11.20 Creating Multithreaded Applications NIIT Implementing Multithreading Multithreading helps to perform various operations simultaneously and saves time of a user A multithreaded program has a main thread and other user-defined threads to perform multiple tasks simultaneously The microprocessor . Creating Multithreaded Applications Chapter 11 A program executes as a single, sequential flow of control synchronization in threads Identify communication between processes Objectives ¤NIIT Creating Multithreaded Applications 11.3 A thread is defined as the execution path of a program. You can define. Each thread in a multithreaded process runs at the same time and maintains a different execution flow. The following figure shows a multithreaded process with two threads. A Multithreaded Process Implementing