欢迎来到淘文阁 - 分享文档赚钱的网站! | 帮助中心 好文档才是您的得力助手!
淘文阁 - 分享文档赚钱的网站
全部分类
  • 研究报告>
  • 管理文献>
  • 标准材料>
  • 技术资料>
  • 教育专区>
  • 应用文书>
  • 生活休闲>
  • 考试试题>
  • pptx模板>
  • 工商注册>
  • 期刊短文>
  • 图片设计>
  • ImageVerifierCode 换一换

    中科大操作系统原理与实现课件4_Threads1.pdf

    • 资源ID:70322501       资源大小:221.62KB        全文页数:38页
    • 资源格式: PDF        下载积分:15金币
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录   QQ登录  
    二维码
    微信扫一扫登录
    下载资源需要15金币
    邮箱/手机:
    温馨提示:
    快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。
    如填写123,账号就是123,密码也是123。
    支付方式: 支付宝    微信支付   
    验证码:   换一换

     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    中科大操作系统原理与实现课件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小结和作业.谢谢!

    注意事项

    本文(中科大操作系统原理与实现课件4_Threads1.pdf)为本站会员(asd****56)主动上传,淘文阁 - 分享文档赚钱的网站仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知淘文阁 - 分享文档赚钱的网站(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    关于淘文阁 - 版权申诉 - 用户使用规则 - 积分规则 - 联系我们

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

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

    收起
    展开