Linux编程多线程.ppt

上传人:qwe****56 文档编号:70008401 上传时间:2023-01-14 格式:PPT 页数:94 大小:2.52MB
返回 下载 相关 举报
Linux编程多线程.ppt_第1页
第1页 / 共94页
Linux编程多线程.ppt_第2页
第2页 / 共94页
点击查看更多>>
资源描述

《Linux编程多线程.ppt》由会员分享,可在线阅读,更多相关《Linux编程多线程.ppt(94页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

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

26、l threads within the same process”To the kernel:PCB1 and PCB 2 are processes(tasks)Java ThreadsJava threads are managed by the JVMJava threads may be created by:Extending Thread classImplementing the Runnable interfaceDetails in textbookLinux Programming Pthread Thread Basic Thread operations includ

27、e thread creation,termination,synchronization,data management Threads in the same process share:Process address space,instructions and most data Opened files Signals and signal handles Each thread has a unique:Thread ID A register set Stack Local variables and return addressPthreads:POSIX ThreadsPth

28、reads is a standard set of C library functions for multithreaded programmingIEEE Portable Operating System Interface,POSIX,section 1003.1 standard,1995Pthread Library(60+functions)Thread management:create,exit,detach,join,.Thread cancellationMutex locks:init,destroy,lock,unlock,.Condition variables:

29、init,destroy,wait,timed wait,.Programs must include the file pthread.hPrograms must be linked with the pthread library(-lpthread)Pthreads Naming ConventionTypes:pthread_object_tFunctions:pthread_object_actionConstants/Macros:PTHREAD_PURPOSEExamples:pthread_t:the type of a threadpthread_create():crea

30、tes a threadpthread_mutex_t:the type of a mutex lockpthread_mutex_lock():lock a mutexPTHREAD_CREATE_DETACHEDPthread POSIX thread Include pthread header file#include Compile and execution C compiler:gcc o foo foo.c-lpthread C+compiler:g+-o foo foo.c lpthread Execution:./fooExamplePthread POSIX thread

31、 Basic pthread functions pthread_create create child thread pthread_exit thread termination pthread_join wait for thread termination phtread_mutex_lock lock critical section pthread_mutex_unlock unlock critical section pthread_cond_wait wait for a condition signal phtread_cond_signal wake up one wai

32、ting thread pthread_cond_broadcast wake up all waiting threadspthread_self()Returns the thread identifier for the calling threadAt any point in its instruction stream a thread can figure out which thread it isConvenient to be able to write code that says:“If youre thread 1 do this,otherwise do that”

33、However,the thread identifier is an opaque object(just a pthread_t value)you must use pthread_equal()to test equalitypthread_t pthread_self(void);int pthread_equal(pthread_t id1,pthread_t id2);pthread_create()Creates a new threadint pthread_create(pthread_t*thread,pthread_attr_t*attr,void*(*start_ro

34、utine)(void*),void*arg);Returns 0 to indicate success,otherwise returns error codethread:output argument for the id of the new threadattr:input argument that specifies the attributes of the thread to be created(NULL=default attributes)start_routine:function to use as the start of the new threadmust

35、have prototype:void*foo(void*)arg:argument to pass to the new thread routineIf the thread routine requires multiple arguments,they must be passed bundled up in an array or a structurepthread_create()exampleWant to create a thread to compute the sum of the elements of an arrayvoid*do_work(void*arg);N

36、eeds three argumentsthe array,its size,where to store the sumwe need to bundle them in a structurestruct arguments double*array;int size;double*sum;pthread_create()exampleint main(int argc,char*argv)double array100;double sum;pthread_t worker_thread;struct arguments*arg;arg=(struct arguments*)calloc

37、(1,sizeof(struct arguments);arg-array=array;arg-size=100;arg-sum=∑if(pthread_create(&worker_thread,NULL,do_work,(void*)arg)fprintf(stderr,”Error while creating threadn”);exit(1);.pthread_create()examplevoid*do_work(void*arg)struct arguments*argument;int i,size;double*array;double*sum;argument=(s

38、truct arguments*)arg;size=argument-size;array=argument-array;sum=argument-sum;*sum=0;for(i=0;iarray=array;arg-size=100;arg-sum=∑if(pthread_create(&worker_thread,NULL,do_work,(void*)arg)fprintf(stderr,”Error while creating threadn”);exit(1);.if(pthread_join(worker_thread,&return_value)fprintf(std

39、err,”Error while waiting for threadn”);exit(1);pthread_join()WarningThis is a common“bug”that first-time pthread programmers encounterWithout the call to pthread_join()the previous program may end immediately,with the main thread reaching the end of main()and exiting,thus killing all other threads p

40、erhaps even before they have had a chance to executepthread_join()WarningWhen creating multiple threads be careful to store the handle of each thread in a separate variableTypically one has an array of thread handlesThat way youll be able to call pthread_join()for each threadAlso,note that the follo

41、wing code is sequential!for(i=0;i num_threads;i+)pthread_create(&(threadsi),.)pthread_join(threadsi,.)Thread AttributesOne of the parameters to pthread_create()is a thread attributeIn all our previous examples we have set it to NULLBut it can be very useful and provides a simple way to set options:I

42、nitialize an attributeSet its value with some Pthread API callPass it to Pthread API functions like pthread_create()pthread_attr_init()Initialized the thread attribute object to the default values int pthread_attr_init(pthread_attr_t*attr);Return 0 to indicate success,error code otherwiseattr:pointe

43、r to a thread attributeDetached ThreadOne option when creating a thread is whether it is joinable or detachedJoinable:another thread can call join on itBy default a thread is joinableDetached:no thread can call join on itLets look at the function that allows to set the“detached state”pthread_attr_se

44、tdetachstate()Sets the detach state attributeint pthread_attr_setdetachstate(pthread_attr_t*attr,int detachstate);returns 0 to indicate success,error code otherwiseattr:input parameter,thread attributedetachstate:can be eitherPTHREAD_CREATE_DETACHEDPTHREAD_CREATE_JOINABLE(default)Detach StateDetache

45、d threads have all resources freed when they terminateJoinable threads have state information about the thread kept even after they finishTo allow for a thread to join a finished thread So-called“no rush to join”So,if you know that you will not need to join a thread,create it in a detached state so

46、that you save resourcesThis is lean-and-mean C,as opposed to hand-holding Java,and every little saving is importantCreating a Detached Thread#include#define NUM_THREAD 25void*thread_routine(void*arg)printf(“Thread%d,my TID is%un”,(int)arg,pthread_self();pthread_exit(0);Creating a Detached Threadint

47、main()pthread_attr_t attr;pthread_t tidsNUM_THREADS;int x;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);phthread_create(&(tidsx),&attr,thread_routine,(void*)x);./should take a while otherwise ./the child may not have time to runMutual Exclusion and PthreadsPthre

48、ads provide a simple mutual exclusion lockLock creation int pthread_mutex_init(pthread_mutex_t*mutex,const pthread_mutexattr_t*attr);returns 0 on success,an error code otherwisemutex:output parameter,lockattr:input,lock attributesNULL:defaultThere are functions to set the attribute(look at the man p

49、ages if youre interested)Linux Programming pthread mutexPthread:LockingLocking a lockIf the lock is already locked,then the calling thread is blockedIf the lock is not locked,then the calling thread acquires it int pthread_mutex_lock(pthread_mutex_t*mutex);returns 0 on success,an error code otherwis

50、emutex:input parameter,lockPthread:LockingJust checkingReturns instead of locking int pthread_mutex_trylock(pthread_mutex_t*mutex);returns 0 on success,EBUSY if the lock is locked,an error code otherwisemutex:input parameter,lockSynchronizing pthreadsReleasing a lock int pthread_mutex_unlock(pthread

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 其他杂项

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁