Linux编程多线程.ppt





《Linux编程多线程.ppt》由会员分享,可在线阅读,更多相关《Linux编程多线程.ppt(94页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、Linux Programming Pthreadwww.rt- TopicsThreadsPthreadPthread MutexPthread Condition variablesPthread Main APILinux Programming ThreadsThreadsOverviewMultithreading ModelsThreading IssuesPthreadsWindows XP ThreadsLinux ThreadsJava ThreadsSingle vs.Multithreaded ProcessesProcess:everything weve seen u
2、p to nowThread:like a process,only shares memory,global variables,files,PIDwith other threads within the same processuse threads or processes?Why use threads instead of processes?Faster context switch Easier to share dataUses less memory and resourcesThread creation faster than process creation Less
3、 things to set-upWhy use processes instead of threads?Different codeRunning on different machinesDifferent ownersLittle communicationSharing memory can lead to obscure bugsUser-level threadsThreads can be provided at the user or kernel levelUser level:kernel knows nothing about threadsImplemented in
4、 a library by somebody without touching the kernelUser library handlesThread creationThread deletionThread schedulingBenefits:Faster creation and schedulingDrawbacks:One thread blocking during I/O blocks all threads in process(even ready-to-run threads)User-level threads(contd)Three primary thread l
5、ibraries:POSIX Pthreads Win32 threads Java threadsKernel-level threadsKernel knows about threadsKernel handles thread creation,deletion,schedulingBenefits:Kernel can schedule another thread if current one does blocking I/OKernel can schedule multiple threads on different CPUs on SMP multiprocessorDr
6、awbacks:Slower to schedule,create,delete than user-levelMost modern OSes support kernel-level threadsWindows XP/2000SolarisLinuxTru64 UNIXMac OS XMultithreading ModelsHow to map kernel-level threads to user-level threads?Many-to-OneOne-to-OneMany-to-ManyMany-to-One ModelMany-to-OneMany user-level th
7、reads mapped to single kernel threadExamples:Solaris Green ThreadsGNU Portable ThreadsAny disadvantages?All block when one blocksAll run on 1 CPUOne-to-one ModelOne-to-OneEach user-level thread maps to a kernel threadExamples:Windows NT/XP/2000LinuxSolaris 9 and laterAny disadvantages?Overhead for c
8、reating threadsMany operating systems limit number of threadsMany-to-Many ModelMany-to-Many ModelAllows many user level threads to be mapped to smaller or equal number of kernel threadsAllows the flexibility of choosing the number of kernel threads allocated to a process“Best of both worlds”Solaris
9、prior to version 9Two-level ModelTwo-level ModelSimilar to many-to-many,but allows a user thread to be bound to kernel threadExamplesIRIXHP-UXTru64 UNIXSolaris 8 and earlierThreading IssuesSemantics of fork()and exec()system callsThread cancellationSignal handlingThread poolsThread-specific dataSema
10、ntics of fork()and exec()Does fork()duplicate only the calling thread or all threads?Some UNIX systems have two versions of fork()exec()usually replaces all threads with new programfork1()fork2()Thread CancellationTerminating a thread before it has finishedE.g.,two cooperating threads,one discovers
11、an errorTwo general approaches:Asynchronous cancellation terminates the target thread immediatelyDeferred cancellation allows the target thread to periodically check if it should be cancelledWhy is this an issue?What if a thread is in the middle ofAllocating resourcesPerforming I/OUpdating a shared
12、data structureThread Cancellation(contd)Essentially,deferred cancellation=“target,please cancel yourself”Occurs when target checks for cancellation signalAllows cancellation at“safe”pointsCalled cancellation points in PthreadsSignal HandlingSignals are used in UNIX to notify a process that a particu
13、lar event has occurredA signal handler is used to process signals1.Signal is generated by a particular event2.Signal is delivered to a process3.Signal is handled(or ignored/blocked)Options:Deliver the signal to the thread to which the signal appliesApplicable with synchronous signals e.g.,illegal me
14、mory accessDeliver the signal to every thread in the processDeliver the signal to certain threads in the processAssign a specific threat to receive all signals for the processThread PoolingWhen design situations arise that could benefit by using many short-lived threads,thread pooling is a useful te
15、chnique.Rather than create a brand new thread for each task,you can have one of the threads from the thread pool pulled out of the pool and assigned to the task.When the thread is finished with task,it adds itself back to the pool and waits for another assignment Benefits of Thread Pooling You can r
16、educe response time because a thread is already constructed and started and is simply waiting for its next task.In the case of an HTTP server,an available thread in the pool can deliver each new file requested Threads are fixed in size at the time of construction.All the threads are started,and then
17、 each goes into a wait state until a task is assigned to it.If all the threads are currently assigned a task,new service requests will put into a wait state until one of the threads finishes its task and returns itself to the pool.Thread PoolsMotivating example:a web server running on an SMP machine
18、To handle each connection:1.Create a new process to handle it too slow,inefficient2.Create a new thread to handle itOption 2 better but still has some problems:Some overhead for thread creation/deletionThread will only be used for this connectionUnbounded number of threads might crash web serverBett
19、er solution:use a thread pool of(usually)fixed sizeThread Pools(contd)Threads in pool sit idleRequest comes in:Wake up a thread in poolAssign it the requestWhen it completes,return it to poolIf no threads in pool available,waitAdvantages:Usually slightly faster to wake up an existing thread than cre
20、ate a new oneAllows the number of threads in the application to be limited by the size of the poolMore sophisticated systems dynamically adjust pool sizeThread-specific DataAllows each thread to have its own copy of dataUseful for implementing protectionFor example,user connects to banks database se
21、rverServer process responds,has access to all accountsMultiple people may be accessing their accounts at the same timeThread assigned to manipulate or view users bank account Using thread-specific data limits(unintentional or erroneous)access by other threadsPthreadsA POSIX standard(IEEE 1003.1c)API
22、 for thread creation and synchronizationNOT an implementationImplementation in different OSes may be using user or kernel threadsCommon in UNIX operating systems(Solaris,Linux,Mac OS X)Fairly portableAvailable on pyriteHas man pages on Linux(check“man pthread_create”)To use:#include Link with pthrea
23、d library:g+prog.cc-lpthreadWindows XP ThreadsImplements the one-to-one mappingEach thread containsA thread idRegister setSeparate user and kernel stacksPrivate data storage areaThe register set,stacks,and private storage area are known as the context of the threadsLinux ThreadsLinux refers to them
24、as tasks rather than threadsThread creation is done through the clone()system callclone()allows a child task to share different things with the parent task such as:the address spacethe table of open filesthe signal handlersIf nothing is shared:same as fork(),creates essentially a processIf everythin
25、g is shared:creates a thread as we know itLinux Threads(contd)int clone(int(*fn)(void*),void*child_stack,int flags,void*arg);clone()is used to create kernel-level threadsopen filesaddress spacePCB1filesmemory spaceopen filesaddress spacePCB2(cloned from PCB1)To the user:PCB1 and PBC2 are“kernel-leve
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Linux 编程 多线程

限制150内