计算机线程外文翻译外文文献英文文献_第1页
计算机线程外文翻译外文文献英文文献_第2页
计算机线程外文翻译外文文献英文文献_第3页
计算机线程外文翻译外文文献英文文献_第4页
计算机线程外文翻译外文文献英文文献_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

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

文档简介

1、Chapter 25 Thread BasicsWhy Does Windows Support Threads?. .691Thread Overhead- .692Stop the Madness . :;.696CPU Trends . 699NUMA Architecture Machines . .700CLR Threads and Windows Threads . .703Usi ng a Dedicated Thread to Perform an AsynchronousCompute-Bound Operation .704Reasons to Use Threads .

2、706Thread Scheduling and Priorities . . .708Foregro und Threads versus Backgro und Threads .713What Now?715In this chapter, I in troduce the basic con cepts concerning threads, and I offer a way for developers to conceptualize about them and their use. I II explain why Microsoft Windowsin troduced t

3、he con cept of threads, CPU tren ds, the relatio nship betwee n com mon Ian guage run time (CLR) threads and Win dows threads, the overhead associated with using threads ,how Win dows schedules threads, the Microsoft .NET Framework classes that expose thread properties, and much more.The chapters in

4、 Part V of this book, Thread in g,” expla in how Win dows and the CLR work together to provide a thread ing architecture. It is my hope that after readi ng these chapters,you will take away a foun dati on of kno wledge that will allow you to effectively use threads to desig n and build resp on sive,

5、 reliable, and scalable applicatio ns and comp onen ts.Why Does Windows Support Threads?Back in the early days of computers, operating systems didn t offer the concept of athread .In effect, there was just one thread of executi on that ran throughout the en tire system, which in cluded both operat i

6、ng system code and applicatio n code. The problem with hav ing only one thread of executi on was that a long-running task would preve nt other tasks from execut ing.For example, in the days of 16-bit Win dows, it was very com mon for an applicati on that was printing a docume nt to stall the en tire

7、 mach ine, caus ing the OS and all other applicati ons to stop resp onding.And, sometimes applicati ons would have a bug in them, result ing in an infin ite loop that also stopped the en tire machi ne from operati ng.At this point, the end user would have no choice but to reboot the computer by pres

8、s ing the reset butt on or power switch. Of course, end users hated doing this (they still do, in fact) because all running applicati ons term in ated; more importa ntly, any data that these applicati ons were process ing was throw n out of memory and lost. Microsoft knew that 16-bit Win dows would

9、not be a good eno ugh operat ing system to keep Microsoft releva nt as the computer in dustry progressed, so they set out to build a new OS to address the n eeds of corporati ons and in dividuals. This new OS had to be robust, reliable, scalable, and secure, and it had to improve the many deficie nc

10、ies of 16-bit Win dows. This OS kernel orig in ally shipped in Microsoft Win dows NT. Over the years, this kernel has had many tweaks and features added to it. The latest vers ion of this kernel ships in the latest vers ions of the Microsoft clie nt and server Win dows operati ng systems.Whe n Micro

11、soft was desig ning this OS kern el, they decided to run each in sta nee of an applicati on in what is called a process A process is just a collecti on of resources that is used by a sin gle in sta nee of an applicati on. Each process is give n a virtual address space, en suri ng that the code and d

12、ata used by one process is not accessible to ano ther process. This makes applicati on in sta nces robust because one process cannot corrupt code or data being used by another. In addition, the OS s kernel code and data are not accessible to processes; therefore,itnot possible for applicati on code

13、to corrupt operat ing system code or data. So no w,applicati on code cannot corrupt other applicati ons or the OS itself, and the whole computi ng experie nee is much better for end users. In additi on, the system is more secure because applicati on code cannot access user n ames, passwords, credit

14、card in formati on, or other sen sitive in formatio n that is in use by ano ther applicati on or the operati ng system itself.This is all well and good, but what about the CPU itself? What if an applicatio n en ters an infin ite loop? Well, if there is on ly one CPU in the machi ne, the n it execute

15、s the infin ite loop and cannot execute any thi ng else, so while the data cannot be corrupted and is more secure,the system could still stop resp onding to the end user. Microsoft n eeded to fix this problem,too, and threads were the an swer. Athread is a Win dows con cept whose job is to virtualiz

16、e the CPU. Win dows gives each process its very own thread (which functions similar to a CPU),a nd if applicati on code en ters an infin ite loop, the process associated with that code freezesup, but other processes (which have their own threads) are not froze n; they keep running!Thread OverheadThr

17、eads are awesome because they en able Win dows to be resp on sive eve n whe n applicati on sare execut ing long-running tasks. Also, threads allow the user to use one applicati on (like Task Man ager) to forcibly kill an applicati on that appears froze n because it is execut ing a long-running task.

18、 But as with every virtualizati on mecha ni sm, threads have space (memory con sumpti on) and time (run time executi on performa nee) overhead associated with them.Let s explore this overhead in more detail now. Every thread has one of each of the followi ng:Thread kernel object The OS allocates and

19、 in itializes one of these data structures for each thread created in the system. The data structure contains a bunch of properties(discussed later in this chapter) that describe the thread. This data structure also contains what is called the thread s con text. The con text is a block of memory tha

20、t contains thet CPU s registers. When Win dows is running on a machi ne with an x86 CPU, thehread s con text uses about 700 bytes of memory. For x64 and IA64 CPUs, the con text is about 1,240 and 2,500 bytes of memory, respectively.Thread en vir onment block (TEB) The TEB is a block of memory alloca

21、ted and in itialized in user mode (address space that applicati on code can quickly access). The TEB con sumes 1 page of memory (4 KB on x86 and x64 CPUs, 8 KB on an IA64 CPU).The TEB con ta ins the head of the thread s ex-teplidlrmg chain. Each try block that the thread enters inserts a node in the

22、 head of this cha in; the node is removed from the cha in whe n the thread exists in the try block. In addition, the TEB contains the thread s thheed storage data as well as some data structures for use by Graphics Device In terface (GDI) and OpenGL graphics. User-mode stack The user-mode stack is u

23、sed for local variables and argume nts passed to methods. It also contains the address in dicati ng what the thread should execute n ext whe n the curre nt method returns. By default, Win dows allocates 1 MB of memory for each thread s umode stack.Kern el-mode stack The kern el-mode stack is also us

24、ed whe n applicati on code passes argume nts to a kern el-mode fun cti on in the operat ing system. For security reas on s,Wi ndows copies any arguments passed from user-mode code to the kernel from thread s user-mode stack to the thread -moeeistlack. Once copied, the kernel can verify thearguments

25、values, and since the application code can t accesiadthetkernelmodeapplication can t modify the arguments values after thegJitiavedbanidhthe OS kernel code beg ins to operate on them .In additi on, the kernel calls methods withi n itself and uses the kernelmode stack to pass its own arguments,to sto

26、re a function s local varialand to store return addresses. The kern el-mode stack is 12 KB whe n running on a 32-bitWin dows system and 24 KB whe n running on a 64-bit Win dows system.DLL thread-attach and thread-detach no tificati ons Win dows has a policy that whe never a thread is created in a pr

27、ocess, all DLLs loaded in that process have their DllMai n method called, pass ing a DLL_THREAD_ATTACH flag. Similarly, whe never a thread dies, all DLLs in the process have their DllMa in method called, pass ing it aDLL_THREAD_DETACH flag. Some DLLs n eed these notificatio ns to perform some specia

28、l in itializatio n or clea nup for each thread created/destroyed in the process. For example,the C-Run time library DLL allocates some thread-local storage state that is required should the thread use functions contained within the C-R un time library.In the early days of Win dows, many processes ha

29、d maybe 5 or 6 DLLs loaded into them,but today, some processes have several hun dred DLLs loaded into them. Right now, on mymachi ne, Microsoft Office Outlook has about 250 DLLs loaded in to its process address space!This means that whe never a new thread is created in Office Outlook, 250 DLL functi

30、ons must get calledbefore the thread is allowed to do what it was created to do. And these 250 functions must be called aga in whe never a thread in Outlook dies. Wo this can seriously affect the performa nee of creati ng and destro ying threads with in a process.So now, you see all the space and ti

31、me overhead that is associated with creati ng a thread, lett ing it sit around in the system, and destro ying it. But the situati on gets eve n worse no wwe re going to start talki ng abouc on text switch ing. A computer with only one CPU in it can do only one thi ng at a time. Therefore, Win dows h

32、as to share the actual CPU hardware among all the threads (logical CPUs) that are sitti ng around in the system.At any give n mome nt in time, Win dows assig ns one thread to a CPU. That thread is allowed to run for a time-slice (sometimes referred to as 卯uan turn). Whe n the time-slice expires,Wi n

33、dows con text switches to ano ther thread. Every con text switch requires that Win dows performs the followi ng acti ons:1. Save the values in thQPU s registers tdhe curre ntly running thread con text structurein side the thread s kernel object.2. Select one thread from the set of existi ng threads

34、to schedule n ext. If this thread is owned by ano ther process, the n Win dows must also switch the virtual address spacesee n by the CPU before it starts executi ng any code or touchi ng any data.3. Load the values in the selected thread s con text structure into the CPU s regthe con text switch is

35、 complete, the CPU executes the selected thread un til its time-sliceexpires, and the n ano ther con text switch happe ns aga in. Win dows performs con text switches about every 30 ms. Con text switches are pure overhead; that is, there is no memory or performa nee ben efit that comes from con text

36、switches. Win dows performs con text switch ing to provide end users with a robust and resp on sive operat ing system.Now, if an application s thread enters into an infinite loop, Windows will periodically preempt that thread, assig n a differe nt thread to an actual CPU, and let this other thread r

37、un for a while. This other thread could be Task Manager s thread and now, the end user can use TaskMan ager to kill the process containing the thread that is in an infin ite loop. When doing this, the process dies and all the data it was work ing on is destroyed, too, but all other processes in the

38、system continue to run just fine without los ing their data. Of course, the user does nhave to reset the mach ine and reboot, so con text switches are required to provide end users with a much better overall experie nee at the cost of performa nee.In fact, the performa nee hit is much worse tha n yo

39、u might thi nk. Yes, a performa nee hit occurs whe n Win dows eon text switches to ano ther thread. But the CPU was execut ing ano ther thread, and the previouslyrunning thread s code and data reside in the CPU so thattheachesCPU does n t have to access RAM memory as much, which has sig nifica nt la

40、teasyiociated with it. When Win dows eon text switches to a new thread, this new thread is most likely executing different code and accessing different data that is not in the CPUCPU s cache.must access RAM memory to populate its cache so it can get back to a good executi on speed.But the n, about 3

41、0 ms later, ano ther eon text switch occurs.The time required to perform a con text switch varies with differe nt CPU architectures and speed. And the time required to build up a CPU s cache depends on what applications arerunning in the system, the size of the CPU s caches, and various other factor

42、s. So it is imposfor me to give you an absolute figure or eve n an estimate as to what time overhead is in curred for each con text switch. Suffice it to say that you want to avoid using con text switches as much as possible if you are in terested in build ing high-perform ing applicati ons and comp

43、 onen ts.Importa nt At the end of a time-slice, if Win dows decides to schedule the same thread aga in( rather tha n switch ing to ano ther thread), the n Win dows does not perform a con text switch .In stead, the thread is allowed to just continue running. This improves performa nee sig nifica ntly

44、, and avoid ing con text switches is someth ing you want to achieve as ofte n as possible whe n you desig n your code.Importa nt A thread can volun tarily end its time-slice early, which happe ns quite freque ntly because threads typically wait for I/O operati ons (keyboard, mouse, file, n etwork, e

45、tc.) to complete. For example, Notepad s thread usually sits idle with nothing to do; this thread is wait ing for in put. If the user presses the J key on the keyboard, Win dowwakes Notepad s thread to have it process the J keystroke. It may take Notepad s thread just 5 ms to prokey, and the n it ca

46、lls a Win32 fun cti on that tells Win dows that it is ready to process the n ext in put eve nt. If there are no more in put eve ntsthe n Win dows puts Notepad s thread into a wait state (reli nq uishi ng the rema in der of its time-slice) so that the thread is not scheduled on any CPU un til the nex

47、t in put stimulus occurs. This improves overall system performa nee since threadsthat are wait ing for I/O operati ons to complete are not scheduled on a CPU and do not waste CPU time; other threads can be scheduled on the CPU in stead.In additi on, whe n perform ing a garbage collecti on, the CLR m

48、ust suspe nd all the threads,walk their stacks to find the roots to mark objects in the heap, walk their stacks aga in( updati ng roots to objects that moved duri ng compacti on), and the n resume all the threads.So avoidi ng threads will greatly improve the performa nee of the garbage collector, to

49、o. And whe never you are using a debugger, Win dows suspe nds all threads in the applicati on being debugged every time a breakpo int is hit and resumes all the threads whe n you sin gle-step or run the applicati on. So the more threads you have, the slower your debugg ing experie nee will be.From t

50、his discussi on, you should con clude that you must avoid using threads as much as possible because they con sume a lot of memory and they require time to create, destroy,a nd man age. Time is also wasted whe n Win dows con text switches betwee n threads and whe n garbage collecti ons occur. However

51、, this discussi on should also help you realize that threads must be used sometimes because they allow Win dows to be robust and resp on sive.I should also point out that a computer with multiple CPUs in it can actually run multiple threads simulta neously, in creas in gscalability (the ability to d

52、o more work in less time).Wi ndows will assig n one thread to each CPU core, and each core will perform its own con text switch ing to other threads. Win dows makes sure that a sin gle thread is not scheduled on multiple cores at one time because this would wreak havoc. Today, computers that con tai

53、 n multiple CPUs, hyperthreaded CPUs, or multi-core CPUs are com mon place. But whe n Win dows was origi nally desig ned, sin gle-CPU computers were com mon place, and Win dows added threads to improve system resp on sive ness and reliability. Today, threads are also being used to improve scalabilit

54、y, which can happe n only on computers that have multiple cores in them.The rema ining chapters in this book discuss the various Win dows and CLR mecha ni sms that exist so that you can effectively wrestle with the tension of creati ng as few threads as possible while still keep ing your code resp o

55、n sive and allow ing it to scale if your code is running on a mach ine with multiple cores.第25章线程基础Win dows为什么要支持线程线程开销停止疯狂CPU发展趋势NUMA架构的机器CLR线程和Windows线程使用专用线程执行异步的计算限制操作使用线程的理由线程调度和优先级前台线程和后台线程继续学习本章将介绍线程的基本概念,帮助开发人员理解线程及其使用。我将解释MicrosoftWin dows为什么引入线程的概念、CPU发展趋势、CLR线程和Win dows线程之间的关系、 与线程的使用关联的开

56、销、Win dows如何调度线程、公开了线程属性的Microsoft .NET Framework类等。本书第V部分”线程处理”的各个章节将解释Windows和CLR如何协同提供一个线程处 理架构。通过这些内容,希望能帮你建立一个良好的基础,使你学会高效率地使用线程来 设计和构建反应灵敏的、可靠的、可伸缩的应用程序和组件。25.1 Windows为什么要支持线程在计算机的早期岁月,操作系统没有提供线程的概念。事实上,整个系统只运行着一 个执行线程,其中同时包含操作系统代码和应用程序代码。只用一个执行线程的问题在于,长时间运行的任务会阻止其他任务执行。例如,在16位Win dows的那些日子,打

57、印一个文档的应用程序很容易 ”冻结”整个机器, 造成OS249和其他应用程序停止响应。有的应用程序含有 bug,会造成无限循环,这同样会 造成整个机器停止工作。遇到这个问题,用户只好按Reset!或电源开关重启计算机。用户们对此感到深恶痛绝(事实上,他们现在一样会),因为所有正在运行的应用程序都会终止。更重要的是,这 些应用程序正在处理的数据都会无端地丢失。Microsoft明白16位Windows不是一个理想的操作系统。随着计算机工业的持续进步,它不足以保持Microsoft的领先地位。所以,他们计划构建一个新的OS来满足企业和个人的需要。这个新的 OS必须健壮、可靠、易于伸缩 以及安全,而

58、且它必须改进16位Windows的许多不足。这个OS内核最初是在Microsoft Win dows NT中发布的。经过多年的发展,这个内核已进行了大量改进,添加了大量功能。 Microsoft每次发布客户端和服务器 Windows操作系统的最新版本时,都会在其中采用了这 个内核的最新版本。Microsoft设计这个OS内核时,他们决定在一个进程中运行应用程序的每个实例。进程不过是应用程序的一个实例要使用的资源的一个集合。每个进程都被赋予了一个虚拟地址 空间,确保一个进程使用的代码和数据无法由另一个进程访问。这就确保了应用程序实例 的健壮性,因为一个进程无法破坏另一个进程使用的代码或数据。除此之外,OS的内核代码和数据是进程访问不到的;所以,应用程序代码破坏不了操作系统代码或数据。由于应 用程序代码破坏不了其他应用程序或者 OS自身,所以用户的计算体验变得更好了。 除此之 外,系统变得比以往更安全,因为应用程序代码无法访问另一个应用程序或者 OS自身使用 的用户名、密码、信用卡资料或者其他敏感信息。听起来似乎不错,但CPU本身呢?如果一个应用程序进入无限循环,会发生什么?如 果机器中只有一个CPU,它会执行无限循环,不能执行其他任何东西。所以,虽然数据无 法被破坏,而且更安全,但系统仍然可能停止响应。Microsoft需要修正这个问题

温馨提示

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

评论

0/150

提交评论