中科大操作系统原理与实现课件4_Threads1.pdf
.操作系统原理与设计第4章 Threads 1(线程1)陈香兰中国科学技术大学计算机学院December 20,2009.提纲OverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.OutlineOverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.Thread concept IIA thread is a basic unit of CPU utilizationIa thread IDIa program counterIa register setIand a stackIIt shares with other threads belonging to the same processIcode sectionIdata sectionIand other OS resourcesIopen files,signals,etc.Thread concept IIISingle threaded VS.Multithreaded processes.Motivation IIOn modern desktop PC,many APPs are multithreaded.Ia seperate process+several threadsIExample 1:A web browserIone for displaying images or text;Ianother for retrieving data from networkIExample 2:A word processorIone for displaying graphics;Ianother for responding to keystrokes from the user;Iand a third for performing spelling&grammer checking in thebackgroundIMotivation,think aboutIa web server,Ian RPC serverIand Javas RMI systems.Motivation IIIPARTICULAR,many OS systems are nowmultithreaded.ISolaris,Linux(伪).Benefits1.Responsiveness(响应度高)IExample:an interactive application such as web browser,whileone thread loading an image,another thread allowing userinteraction2.Resource SharingIaddress space,memory,and other resources3.EconomyISolaris:creating a process is about 30 times slower then creating athread;context switching is about 5 times slower4.Utilization of MP ArchitecturesIparallelism and concurrency.OutlineOverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.Two Methods IITwo methods to support threadsIUser threadsIKernel threadsIUser threadsIThread management done by user-level threads librarywithout kernel supportIKernel may be multithreaded or not.IThree primary thread libraries:IPOSIX PthreadsIWin32 threadsIJava threads.Two Methods IIIKernel ThreadsISupported by the Kernel,usually may be slower then userthreadIExamplesIWindows XP/2000ISolarisILinux(伪)ITru64 UNIX(formerly Digital UNIX)IMac OS X.Multithreading Models IIThe relationship between user threads and kernel threadsIMany-to-OneIOne-to-OneIMany-to-ManyIMany-to-OneIMany user-level threadsmapped to single kernelthreadIExamples:ISolaris Green ThreadsIGNU Portable Threads.Multithreading Models IIIOne-to-OneIEach user-level thread maps to a kernel threadIExamplesIWindows NT/XP/2000ILinuxISolaris 9 and later.Multithreading Models IIIIMany-to-Many ModelIAllows many user level threads to bemapped to many kernel threadsIAllows the operating system to create asufficient number of kernel threadsIExamplesISolaris prior to version 9IWindows NT/2000 with the ThreadFiberpackage.Multithreading Models IVITwo-level Model,a popular variationon many-to-many modelISimilar to M:M,except that it allowsa user thread to be bound to akernel threadIExamplesIIRIXIHP-UXITru64 UNIXISolaris 8 and earlier.OutlineOverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.Thread Libraries.IA thread library provides the programer an API for creatingand managing threads.ITwo primary ways1.to provide a library entirely in user space with no kernelsupport2.to implement a kernel-level library supported directly by theOSlibrarycode&dataAPIinvoking method inside APIuser-levelentirely in user spaceuser spacea local function callkernel-levelkernel spaceuser spacesystem callIThree main thead librariesIPOSIX PthreadsIWin32 threadsIJava threads.PthreadsIA POSIX standard(IEEE 1003.1c)API for thread creationand synchronizationIAPI specifies behavior of the thread library,implementation isup to development of the libraryICommon in UNIX OSes(Solaris,Linux,Mac OS X).Multithreaded C program using the Pthreads API I#include#include int sum;/*this data is shared by the thread(s)*/void*runner(void*param);/*the thread*/int main(int argc,char*argv)pthread t tid;/*the thread identifier*/pthread attr t attr;/*set of attributes for the thread*/if(argc!=2)fprintf(stderr,”usage:a.out n”);return-1;if(atoi(argv1)0)for(i=1;i=upper;i+)sum+=i;pthread exit(0);.pthread attr init.NAMEpthread attr init,pthread attr destroy-initialise and destroy threads attributeobjectSYNOPSIS#include int pthread attr init(pthread attr t*attr);int pthread attr destroy(pthread attr t*attr);DESCRIPTIONThe function pthread attr init()initialises a thread attributes object attr withthe default value for all of the individual attributes used by a givenimplementation.The pthread attr destroy()function is used to destroy a thread attributesobject.RETURN VALUEUpon successful completion,both return a value of 0.Otherwise,an error number is returned to indicate the error.pthread create().NAMEpthread create-thread creationSYNOPSIS#include int pthread create(pthread t*thread,const pthread attr t*attr,void*(*start routine)(void*),void*arg);DESCRIPTIONThe pthread create()function is used to create a new thread,with attributesspecified by attr,within a process.Upon successful completion,pthread create()stores the ID of the created thread in the location referencedby thread.The thread is created executing start routine with arg as its sole argument.If pthread create()fails,no new thread is created and the contents of thelocation referenced by thread are undefined.RETURN VALUEIf successful,the pthread create()function returns zero.Otherwise,an error number is returned to indicate the error.pthread join.NAMEpthread join-wait for thread terminationSYNOPSIS#include int pthread join(pthread t thread,void*value ptr);DESCRIPTIONThe pthread join()function suspends execution of the calling thread until thetarget thread terminates,unless the target thread has already terminated.The results of multiple simultaneous calls to pthread join()specifying the sametarget thread are undefined.RETURN VALUEIf successful,the pthread join()function returns zero.Otherwise,an error number is returned to indicate the error.pthread exit.NAMEpthread exit-thread terminationSYNOPSIS#include void pthread exit(void*value ptr);DESCRIPTIONThe pthread exit()function terminates the calling thread and makes the valuevalue ptr available to any successful join with the terminating thread.RETURN VALUEThe pthread exit()function cannot return to its caller.Win32 Threads IISimilar to the Pthreads technique.IMultithreaded C program using the Pthreads API#include#include DWORD Sum;/*data is shared by the thread(s)*/*the thread runs in this separate function*/DWORD WINAPI Summation(PVOID Param)DWORD Upper=*(DWORD*)Param;for(DWORD i=0;i=Upper;i+)Sum+=i;return 0;int main(int argc,char*argv)DWORD ThreadId;HANDLE ThreadHandle;.Win32 Threads IIint Param;/do some basic error checkingif(argc!=2)fprintf(stderr,”An integer parameter is requiredn”);return-1;Param=atoi(argv1);if(Param=0 is required n”);return-1;/create the threadThreadHandle=CreateThread(NULL,/default security attribute0,/default stack sizeSummation,/thread function&Param,/parameter to thread function0,/default creation flags&ThreadId);.Win32 Threads IIIif(ThreadHandle!=NULL)WaitForSingleObject(ThreadHandle,INFINITE);CloseHandle(ThreadHandle);printf(“sum=%dn”,Sum);.Java ThreadsIThreads are the fundamental model for program executionin a Java program.IJava threads may be created by:IExtending Thread classIto create a new class that is derived from the Thread classand override its run()method.IImplementing the Runnable interface Java.Example Iclass Sumprivate int sum;public int get()return sum;public void set(int sum)this.sum=sum;class Summation implements Runnableprivate int upper;private Sum sumValue;public Summation(int upper,Sum sumValue)if(upper 0)throw new IllegalArgumentException();this.upper=upper;.Example IIthis.sumValue=sumValue;public void run()int sum=0;for(int i=0;i=upper;i+)sum+=i;sumValue.set(sum);public class Driver public static void main(String args)if(args.length!=1)System.err.println(“Usage Driver”);System.exit(0);Sum sumObject=new Sum();int upper=Integer.parseInt(args0);Thread worker=new Thread(new Summation(upper,sumObject);.Example IIIworker.start();try worker.join();catch(InterruptedException ie)System.out.println(“The sum of”+upper+“is“+sumObject.get();.OutlineOverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.Threading Issues IISemantics of fork()and exec()system callsIDoes fork()duplicate only the calling thread or all threads?ISome UNIX system have chosen to have two versionsIWhich one version to use?Depend on the APP.IThread cancellationITerminating a thread before it has finishedITwo general approaches:IAsynchronous cancellation terminates the target threadimmediatelyIDeferred cancellation allows the target thread to periodicallycheck if it should be cancelledISignal HandlingISignals are used in UNIX systems to notify a process that aparticular event has occurred:ISynchronous:illegal memory access,division by 0.Threading Issues IIIAsynchronous:Ctrl+CIAll signals follow the same pattern:1.Signal is generated by particular event2.Signal is delivered to a process3.Signal is handledISignal handler may be handled byIa default signal handlerIa user-defined signal handlerIWhen multithread,where should a signal be delivered?IDeliver the signal to the thread to which the signal appliesIDeliver the signal to every thread in the processIDeliver the signal to certain threads in the processIAssign a specific threa to receive all signals for the processIThread PoolsICreate a number of threads in a pool where they await workIAdvantages:.Threading Issues IIIIUsually slightly faster to service a request with an existingthread than create a new threadIAllows the number of threads in the application(s)to bebound to the size of the poolIThread Specific DataIAllows each thread to have its own copy of dataIUseful when you do not have control over the thread creationprocess(i.e.,when using a thread pool)IScheduler ActivationsIBoth M:M and Two-level models require communication tomaintain the appropriate number of kernel threads allocated tothe applicationIScheduler activations provide upcalls-a communicationmechanism from the kernel to the thread libraryIThis communication allows an application to maintain thecorrect number kernel threads.OutlineOverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.小结OverviewMultithreading ModelsThread LibrariesThreading Issues小结和作业.谢谢!