ProgrammingC#3.0-21-of1A-2013.ppt_第1页
ProgrammingC#3.0-21-of1A-2013.ppt_第2页
ProgrammingC#3.0-21-of1A-2013.ppt_第3页
ProgrammingC#3.0-21-of1A-2013.ppt_第4页
ProgrammingC#3.0-21-of1A-2013.ppt_第5页
已阅读5页,还剩17页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Ch. 21 Threads and Synchronization,天津大学软件学院 章亦葵 email: ,19:13,1,Chapter 21 Threads and Synchronization Introduction,Threads are responsible for multitasking within a single application. The System.Threading namespace provides a wealth of classes and interfaces to manage multi-threaded programming. C

2、ontents of this chapter First, it will tell you how to create, manage, and kill threads. Second , it focuses on synchronization and prevent dead lock.,19:13,2,Chapter 21 Threads and Synchronization,19:13,3,Threads Threads are typically created when you want a program to do two things at once. For ex

3、ample, calculating pi to the 10billionth place. Another common place to use threading is when you must wait for an event, such as user input, a read from a file, or receipt of data over the network. If you have a single-processor machine (as most users do), computing these values in multiple threads

4、 will certainly run slower than computing one and then the other in a single thread because the processor must switch back and forth between the two threads. This incurs some overhead.,Chapter 21 Threads and Synchronization,19:13,4,Starting Threads: Example 21-1 The simplest way to create a thread i

5、s to create a new instance of the Thread class. The ThreadStart delegate declaration is: Create a new thread: Using namespace System.Threading,public delegate void ThreadStart();,Thread myThread = new Thread( new ThreadStart(Incrementer) ); myThread.Start(); Class AbcClass public void Incrementer( )

6、 for (int i =0;i1000;i+) Console.WriteLine(Incrementer: 0, i); ,Create new thread with a ThreadStart delegate. This in turn initialized to the respective classs member function. Note: This is initialization, does not start thread.,Call Start method to run the thread.,Chapter 21 Threads and Synchroni

7、zation,19:13,5,Joining Threads When you tell a thread to stop processing and wait until a second thread completes its work, you are said to be joining the first thread to the second. It is as though you tied the tip of the first thread onto the tail of the second, hence “joining” them. To join threa

8、d 1 (t1) onto thread 2 (t2), write:,t1() t2.Join(); ,t1. start,t2 start,t1 continue,t2.Join,t2 exit,t1 exit,Chapter 21 Threads and Synchronization,19:13,6,Blocking Threads with Sleep: Example 21-1A The Thread class offers a public static method, Sleep, for just this purpose. The Sleep method is over

9、loaded; one version takes an int, the other a TimeSpan object.,Syntax2: public static void Sleep( TimeSpan timeout);,Syntax1: public static void Sleep( int millisecondsTimeout );,TimeSpan .ctor.: public TimeSpan( int hours, int minutes, int seconds); e.g., TimeSpan elapsedTime = new TimeSpan( 1, 2,

10、3 ); /1H:2M:3S Note: TimeSpan have totally 4 overloaded constructors.,Sleep()Suspends the current thread for a specified time.,Killing Threads: Example21-2A-revised Typically, threads die after running their course. Use a keepalive flag, check the flag periodically. Use Thread.Interrupt() method, as

11、k the thread to kill itself. When thread is blocked in wait, sleep, or join state, ThreadInterruptedException will be thrown, which the thread can catch. Use Thread.Abort() method, this causes ThreadAbortException exception to be thrown, which the thread can catch.,19:13,7,Chapter 21 Threads and Syn

12、chronization,Killing Threads Notes:,19:13,8,Note1: A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have

13、terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.,Note2: Thread.Interrupt() If the thread is not currently blocked in a wait, sleep, or join state, it will be interrupted when it next begins to block. ThreadInterruptedExceptio

14、n is thrown in the interrupted thread, but not until the thread blocks. If the thread never blocks, the exception is never thrown, and thus the thread might complete without ever being interrupted.,Chapter 21 Threads and Synchronization,Example 21-2 bugs,19:13,9,foreach (Thread myThread in myThreads

15、) myThread.IsBackground = true; myThread.Start(); myThread.Name = Thread + ctr.ToString(); ctr+; Console.WriteLine(Started thread 0,myThread.Name); Thread.Sleep(50); ,foreach (Thread myThread in myThreads) myThread.IsBackground = true; myThread.Name = myThread + ctr.ToString()+; Console.WriteLine(St

16、arted thread 0,myThread.Name); myThread.Start(); ctr+; Thread.Sleep(50); ,Chapter 21 Threads and Synchronization,Set Thread name after thread start.,Chapter 21 Threads and Synchronization,19:13,10,Synchronization When we want to control access to a resource, such as an objects properties or methods,

17、 so that only one thread at a time can modify or use that resource. Synchronization is provided by a lock on the object, which helps the developer avoid having a second thread barge in(闯入,打岔) on your object until the first thread is finished with it. This section examines 3 synchronization mechanism

18、s: the Interlock class The C# lock statement The Monitor class,Shared resource,19:13,11,Chapter 21 Threads and Synchronization,Class Tester private int counter; void Incrementer() counter +; ,Tester t private int counter; thread t1 : Incrementer(); thread t2 : Incrementer(); ,实例化的Tester对象,线程1和线程2 共享

19、的counter,实例化,Chapter 21 Threads and Synchronization,19:13,12,Synchronization: Example 21-3 not synchronized,public void Increment() try while (counter 1000) /- Original 21-3 not Synchronized- int temp = counter; temp+; / increment / simulate some work in this method Thread.Sleep(1); / assign the dec

20、remented value and display the results counter = temp; / assign the incremented value and display the results Console.WriteLine(Thread 0. Incrementer: 1,Thread.CurrentThread.Name, temp); ,/Output Thread ThreadOne. Incrementer: 1 Started thread ThreadOne Thread ThreadOne. Incrementer: 2 Started threa

21、d ThreadTwo Thread ThreadOne. Incrementer: 3 Thread ThreadTwo. Incrementer: 3 Thread ThreadOne. Incrementer: 4 Thread ThreadTwo. Incrementer: 4 Thread ThreadOne. Incrementer: 5 Thread ThreadTwo. Incrementer: 5 . Thread ThreadOne. Incrementer: 1000 Thread ThreadOne Exiting. Thread ThreadTwo. Incremen

22、ter: 1000 Thread ThreadTwo Exiting. All my threads are done.,Chapter 21 Threads and Synchronization,19:13,13,Synchronization: Example 21-3 InterLocked,public void Increment() try /InterLocked while (counter 1000) /- Using Interlocked - int temp = Interlocked.Increment(ref counter); / simulate some w

23、ork in this method Thread.Sleep(0); / assign the incremented value and display the results Console.WriteLine(Thread 0. Incrementer: 1,Thread.CurrentThread.Name, temp); ,/Output Started thread ThreadOne Thread ThreadOne. Incrementer: 1 Started thread ThreadTwo Thread ThreadOne. Incrementer: 2 Thread

24、ThreadTwo. Incrementer: 3 Thread ThreadOne. Incrementer: 4 Thread ThreadTwo. Incrementer: 5 Thread ThreadOne. Incrementer: 6 Thread ThreadTwo. Incrementer: 7 . Thread ThreadOne. Incrementer: 998 Thread ThreadTwo. Incrementer: 999 Thread ThreadTwo Exiting. Thread ThreadOne. Incrementer: 1000 Thread T

25、hreadOne Exiting. All my threads are done.,Chapter 21 Threads and Synchronization,19:13,14,Synchronization: Example 21-3 lock statement,public void Increment() try /not synchronized while (counter 1000) /- Using Locks - int temp; lock (this) temp = counter; temp+; Thread.Sleep(1); counter = temp; /

26、assign the incremented value and display the results Console.WriteLine(Thread 0. Incrementer: 1,Thread.CurrentThread.Name, temp); ,/Output Thread ThreadOne. Incrementer: 1 Started thread ThreadOne Thread ThreadOne. Incrementer: 2 Thread ThreadOne. Incrementer: 3 Thread ThreadOne. Incrementer: 10 Thr

27、ead ThreadOne. Incrementer: 11 Started thread ThreadTwo Thread ThreadOne. Incrementer: 12 Thread ThreadTwo. Incrementer: 13 . Thread ThreadOne. Incrementer: 999 Thread ThreadTwo. Incrementer: 1000 Thread ThreadTwo Exiting. Thread ThreadOne. Incrementer: 1001 Thread ThreadOne Exiting. All my threads

28、are done.,calls Monitor.Enter,calls Monitor.Exit,Using Monitor(1) For the most sophisticated(复杂) control over resources, using Monitor method. A monitor lets you decide when to enter and exit the synchronization, and it lets you wait for another area of your code to become free. To begin synchroniza

29、tion, call the Enter() method of the monitor, passing in the object you want to lock:,19:13,15,Chapter 21 Threads and Synchronization,Monitor.Enter(this); /this is the object want to lock,Using Monitor(2): Example 21-4 , 21-4A Choose Wait() for waiting the monitor to become available. Calls Pulse()

30、to notify a thread(the thread who calls Wait method) of in the waiting queue a change in the locked objects state. Pulse:脉冲 When a thread is finished with the monitor. it must mark the end of its controlled area of code with a call to Exit():,19:13,16,Chapter 21 Threads and Synchronization,Monitor.E

31、xit(this);,Monitor.Pulse(this);,Monitor.Wait(this);,Important Note about Monitor:,19:13,17,The Monitor class does not maintain state indicating that the Pulse method has been called. Thus, if you call Pulse when no threads are waiting, the next thread that calls Wait blocks as if Pulse had never bee

32、n called. If two threads are using Pulse and Wait to interact, this could result in a deadlock. Contrast this with the behavior of the AutoResetEvent class: If you signal an AutoResetEvent by calling its Set method, and there are no threads waiting, the AutoResetEvent remains in a signaled state unt

33、il a thread calls WaitOne, WaitAny, or WaitAll. The AutoResetEvent releases that thread and returns to the unsignaled state.,Chapter 21 Threads and Synchronization,Race Conditions and Deadlocks The .NET library provides sufficient thread support such that you will rarely find yourself creating your own threads or managing synchronization manually. Thread synchronization can be tricky(非常复杂), especially in complex programs.,19:13,18,Chapter 21 Threads and Synchronization,If you do decide to create yo

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论