




下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、1 1.1 线程的定义Threads can best be described as “lightweight ses”. The IX-notion of a s has been found to be inconvenient, if not inadequate for applications in distributed systems development. The needs of these applications best served by threads,1 1.1 线程的定义Threads can best be described as “lightweigh
2、t ses”. The IX-notion of a s has been found to be inconvenient, if not inadequate for applications in distributed systems development. The needs of these applications best served by threads, which generalize the notion of a s t it can ted with multiple activities. The popularity of threads has resul
3、ted in ion on UNIX systems and thread libraries are now widely available to programmers for the development of concurrent applications.1.2 ThreadsThreadscan be implementedinone of two1.User-levelThere is no kernel support for multi-threaded ses. Hence, the kernel smulti-implemented in a library of p
4、rocedures linked pplication programs. The has no knowledge of lightweight ses (threads), and therefore cannot them independently. Athreads run-time anizes the scheduling of threads. thread would block the s and therefore all threads within it if itmade a system call, so the asynchronous I/O faciliti
5、es of UNIX are used. The disadvantage of this scheme t threads within a s cannot take advantage amulti-Theadvantages(系统消耗小)Certain thread operations are significantly less costly. le, switching n threads belonging to the same s do sarilyinvolve a system call,and avethisover-(可以修改以适应特殊的应用)User-level
6、thread implemenions can be customized or changed to suit the particular application requirements. This particularly useful for real-time multimedia sing etc. Also, it tosupport manymoreuser-level ncanby default bya2. Kernel-levelThis ion allows threads within different ses to be according to a singl
7、e scheme of relative prioritizing. This ited for exploiting concurrence of Most of the current thread library ions available today user-level threads. tosupport manymoreuser-level ncanby default bya2. Kernel-levelThis ion allows threads within different ses to be according to a single scheme of rela
8、tive prioritizing. This ited for exploiting concurrence of Most of the current thread library ions available today user-level threads. There have been several research ve some formofKernel-level threads. Notableamong these aretheMach distributedOS, which combines the advantages of user-level and ker
9、nel-level threads by user-level code to provide scheduling s to the kernel thread scheduler. providing such a two-level scheduling scheme, the kernel retains control over allocation of sor time, but also allows a s to take advantage of 1.3 LinuxXavier Leroy at INRIA (Paris, France), with input from
10、Pavel Krauz, Richard Henderson others, has developed a Pthreads t implements the One-to-One , allowing it take advantage of multiple sors. It is based on the new Linux system call, clone()2 . runs on Linux 2.0 and up, el, Alpha, SPARC, m68k, and MIPS machines. One ion itsnon-standardionofsignalLinux
11、Threadsfollowsthe so-calledone-to-one:each thread uallya separate sin the kernel. The kernel scheduler takes care of scheduling the threads, just like it regular ses. The threads are created with the Linux clone() system call, which is generalizationof fork() allowing the new signalhandlersofthe s t
12、o share the memoryspace,file descriptors, Advantagesoftheone-to-oneMinimaloverhead on ensive singbout one Asimple and robust ion (the kernel scheduler does most of the hard work The maindisadvantageis moreexpensivecontextswitches onmutexandconditionustgothrough the kernel.This is mitigatedby the tco
13、ntexthe kernelarepretty2 clone unsignedlongclone_flags=regs.ebx; newsp = regs.ecx;if2 clone unsignedlongclone_flags=regs.ebx; newsp = regs.ecx;ifnewsp= 与系统调用clone功能相似的系统调用有fork,但fork事实上只是clone的功能的一部分, 系统定义的几个 clone_flags 标志:置起 CLONE_VM 标志:*SetuptheLDTdescriptorfortheclonecopy_segments(nr, tsk, NULL)
14、; 3 Linux3.1 LinuxThreadsix1003.1c 3 Linux3.1 LinuxThreadsix1003.1c 3.2 /*Argumentspassedtothreadcreationroutine/*Thetypeofthreaddescriptors struct_pthread_descr_struct (略/*Thetypeofthreadhandles.typedefstructpthread_handle_struct* struct_pthread_fastlockh_lock;/*Fastlockforsychronizeds char */*Thre
15、addescriptororNULLifinvalid/*Lowesthestackthread/*Thetypeofmessagessenttothethreadmanagerthreadstruct pthread_request enum ngtherequest/*Requestkind req_kind; union structT, constpthread_attr_t*attr;/*threadattributesvoid*(*fn)(void*); void * arg;sigset_tstruct pthread_treq_kind; union structT, cons
16、tpthread_attr_t*attr;/*threadattributesvoid*(*fn)(void*); void * arg;sigset_tstruct pthread_t free; structvoidstartfunctionargumenttostartfunction*/ signal mask */*ForREQ_FREE:identifierofthreadtofreeexitus/*ForT:thesemaphore/*Oneendofpeforsendingrequeststothethreadmanager. pthread_manager_request=-
17、/*Otherendofpeforsendingrequeststothethreadmanager. #define(2 *1024*#define(4* /*Attributesfortypedef struct sched_param size_t stackaddr_set; void* size_t 3.2.2/*Threadcreation void*(*start_routine)(void*),size_t 3.2.2/*Threadcreation void*(*start_routine)(void*),voidpthread_descrself=thread_self()
18、; struct pthread_request request;if( pthread_manager_request0)if( pthread_initialize_manager()raise( /*Wesuspendourselfandgdbwillwakeusupwhenitreadytohandleus./*Synchronizedebuggingofthethreadmanager*/ request.req_kind = REQ_DEBUG; libc_write( pthread_manager_request,(char*)&request,returnicvoidstru
19、ctsigactionsa; sigset_t mask; struct rlimit limit;/*Ifalreadydonereadytohandleus./*Synchronizedebuggingofthethreadmanager*/ request.req_kind = REQ_DEBUG; libc_write( pthread_manager_request,(char*)&request,returnicvoidstructsigactionsa; sigset_t mask; struct rlimit limit;/*Ifalreadydone(e.g.byaconst
20、ructorcalledr!),bailoutif( !=NULL) pthread_has_cas=compare_and_swap_is_available(); /* For the initial stack, east STACK_SIZE bytes of stack below the current address,and tonaSTACK_SIZEboundary. =/*PlaywiththestacksizelimittomaketnostackeverSTACK_SIZEminustwopages(onepageforthethread,andone pagetoag
21、uardpage). max_stack=STACK_SIZE-2* getpagesize(); if (limit.rlim_cur max_stack) limit.rlim_cur = max_stack; /*Updatethedescriptorfortheinitialthread. _= sing,tfor/*Ifwehavelthread_selfhreadnow. #ifdefINIT_THREAD_SELF(& pthread_initial_thread,/*Theerrno/h_errnovariableofthehreadaretheglobal pthread_i
22、nitial_thre #ifdef SIGRTMIN_errnop=_h_errnop=/*Allocatethesignals pthread_sig_restart= /*Theerrno/h_errnovariableofthehreadaretheglobal pthread_initial_thre #ifdef SIGRTMIN_errnop=_h_errnop=/*Allocatethesignals pthread_sig_restart= libc_allocate_rtsig pthread_sig_cancel= libc_allocate_rtsig pthread_
23、sig_debug= libc_allocate_rtsig(1); if ( pthread_sig_restart 0 | pthread_sig_cancel 0 pthread_sig_debug 0) sa.sa_flags= sigaction( pthread_sig_debug,&sa,/*Initially,block pthread_sig_restart.Willbeunblockedondemand.*/ sigaddset(&mask, pthread_sig_restart); sigprocmask(SIG_BLOCK,&mask,NULL);/*Register
24、anexitfunctionto sigaction( pthread_sig_debug,&sa,/*Initially,block pthread_sig_restart.Willbeunblockedondemand.*/ sigaddset(&mask, pthread_sig_restart); sigprocmask(SIG_BLOCK,&mask,NULL);/*Registeranexitfunctiontokillallother threads.tearlytuser-registeredatexitfunctionsarebefore s.s, pthread_handl
25、e_create(pthread_t*thread,constpthread_attr_t*attr, void * (*start_routine)(void *), void *arg,sigset_t*);pthread_descrnew_thread; pthread_t new_thread_id; char *guardaddr = NULL; size_t guardsize = 0;pagesize = checkwhetherwehavetochange thepolicyandifyes,we cando this.Normally this should be done
26、by examining the returnvalueofthe sched_setschedulercallinpthread_start_thread but this is hard to implement.we cando this.Normally this should be done by examining the returnvalueofthe sched_setschedulercallinpthread_start_thread but this is hard to implement.if(attr!=NULL&attr- schedpolicy!=SCHED_
27、OTHER&geteuid()!=0) return EPERM;/*Findafreesegmentforthethread,andallocateastackifneededfor (sseg = 2; ; sseg+)if(sseg=returnif( pthread_handlessseg.h_descr!=NULL) &guardaddr, &guardsize) = 0) /* Allocate new thread identifier */分配新线程的标识符 new_thread_id = sseg + pthread_threads_counter;/*Initializet
28、hethreaddescriptor*/初始化新线程描述符 new_thread-p_nextwaiting = NULL;new_thread-p_priority = 0;new_thread-p_lock=&( pthread_handlessseg.h_lock); new_thread-p_signal = 0;new_thread-p_signal_jmp = new_thread-p_cancel_jmp=NULL; new_thread-p_terminated = 0;new_thread-p_detached=attr=NULL?0:attr- detachs new_th
29、read-p_exited = 0;new_thread-p_retval = NULL; new_thread-p_joining= e = PTHREAD_CANCEL_ENABLE; new_thread-p_canceled = 0;new_thread-p_errno = 0; new_thread-p_in_sighandler=NULL; new_thread-p_sigwaiting = 0; new_thread-p_guardaddr=guardaddr; new_thread-p_guardsize = guardsize;new_thread-p_userstack=a
30、ttr!=NULL&attr- stackaddr_set; memset (new_thread-p_specific, 0,PTHREAD_KEY_1STLEVEL_SIZE*sizeofnew_thread-p_in_sighandler=NULL; new_thread-p_sigwaiting = 0; new_thread-p_guardaddr=guardaddr; new_thread-p_guardsize = guardsize;new_thread-p_userstack=attr!=NULL&attr- stackaddr_set; memset (new_thread
31、-p_specific, 0,PTHREAD_KEY_1STLEVEL_SIZE*sizeof(new_thread-p_specific0); new_thread-p_self = new_thread;new_thread-p_nr=/*Initializethethreadhandle pthread_init_lock(& /*Determineschedulingparametersforthethreadnew_thread-p_start_args.schedpolicy=-1; if (attr != NULL) switch(attr- inheritsched)case
32、new_thread-p_start_args.schedpolicy=attr- memcpy(&new_thread-p_start_args.schedparam,&attr- schedparam, sizeof (struct sched_param);case/*schedpolicydoesntneedtobeset,onlygetpriority /*Finishsettingupargumentstopthread_start_thread new_thread-p_start_args.arg = arg; /*Dothecloning*/= clone(pthread_s
33、tart_thread,(void*) /*Checkifcloningsucceededif=-1)/*Freethestackifweallocateditif(attr=NULL|!attr- /*Freethestackifweallocateditif(attr=NULL|!attr- pthread_handles_num-; return errno;/*Insertnewthreadindoublylinkedlistofactivethreadsnew_thread-p_prevlive= new_thread-p_nextlive= pthread_main_thread-
34、 /*fieldofthenewthread,incasewegettherebeforechildstarts.*/ /*Wereallset=;return3.4 Pthread_initial_thread (CS-2*STACK_SIZE)&(STACK_SIZE-Current s pthread_descrdefault_new_thread, pthread_descr*out_new_thread, char*out_new_thread_bottom, char * out_guardaddr,size_t*pthread_descr new_thread; char*new
35、_thread_bottom; char * guardaddr;size_tstacksize,if(attr!=NULL&s pthread_descrdefault_new_thread, pthread_descr*out_new_thread, char*out_new_thread_bottom, char * out_guardaddr,size_t*pthread_descr new_thread; char*new_thread_bottom; char * guardaddr;size_tstacksize,if(attr!=NULL&attr- /*The new_thr
36、ead(pthread_descr) (long)(attr- stackaddr) & -sizeof(void *) - 1; new_thread_bottom = (char *) attr- stackaddr - attr- stacksize; guardaddr = NULL;guardsize= /*Allocatespaceforstackandthreaddescriptoratdefaultaddressnew_threaddefault_new_thread;new_thread_bottom=(char*)new_thread-INITIAL_STACK_SIZE,
37、 PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_GROWSDOWN, -1, 0) = MAP_FAILED)/*Badluck,thissegmentisalreadymapped.*/ return -1;/*We manage togeta stack. Nowseewhetherweneedaandallocateitifsary. ttheattributes(stack_size=STACK_SIZEsizeguardsize=pagesize)donotneeda
38、guardpage,since the RLIMIT_STACK soft limit prevents stacksfromooneanother.if (attr = NULL |attr- guardsize=0(attr- guardsize=pagesize attr- stacksize=STACK_SIZE-/*Wedontneedaguardpage.*/ guardaddr = NULL;guardsize=attr- stacksize=STACK_SIZE-/*Wedontneedaguardpage.*/ guardaddr = NULL;guardsize=/*Put
39、a ageatthebottomofthestackstacksize=roundup(attr- stacksize,pagesize); if (stacksize = STACK_SIZE - pagesize)stacksize = STACK_SIZE - pagesize; guardaddr=(void*)new_thread-stacksize; guardsize = attr- guardsize; =/*Wedontmakethisanerror. */ guardaddr = NULL;guardsize=*out_new_thread= *out_guardaddr=
40、return 0;缺省保护页(1 保护页(可选3.5 4 问题及发4.1 LinuxThreads3.5 4 问题及发4.1 LinuxThreadsclone() 的 On recent kernels (late 2.1 kernels and ing 2.2 kernels), n 32 signals are he form of realtime realtime signals for When run on one of those kernels, LinuxThreads uses ernal operation, thus leaving SIGUSR1 and SIGUS
41、R2 free for user code. parentcauseproblemswith/procandsignalsgotoD 现在,实现时使用了两个信号SIGUSR1andSIGUSR2 用512。 1- Synchronous signals (generated by the thread execution, e.g. SIGFPE) are delivered to traisedthem.2- Afatal asynchronous signal terminates all he s. (OK. The thread whenathreaddiesonasignalandk
42、illsallotherthreadswiththe same3-Anasynchronoussignalwillbedeliveredtooneofthethreadsoftheprogramwhichdoesblockthesignal(itisunspecifiedwhich).(No,thesignalisdeliveredtothethreaditsbeensentwhich based on remainsd of the thread. t thread is currently blocking the signal, the 4-Thesignalwillbedelivere
43、dtoatmostonethread.(OK,exceptforsignalsgeneratedfromterminalorsenttothesgroup,whichwillbedeliveredtoall-The current ion ofwhich based on remainsd of the thread. t thread is currently blocking the signal, the 4-Thesignalwillbedeliveredtoatmostonethread.(OK,exceptforsignalsgeneratedfromterminalorsenttothesgroup,whichwillbedeliveredtoall-The current
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 电子商务行业商品退换货免责条款
- 探索科学纪录片观后感和科普启示
- 社交网络对青少年自尊心的影响分析
- 公共服务资源配置与优化措施
- 社交网络系统在文化传播中的运营艺术
- 特定目标市场营销策划合同
- 小学生节日庆祝活动征文
- 二零二五年度生鲜农产品质量安全认证服务合同3篇
- 非营利组织保密管理措施探讨
- 儿童餐饮服务质量委员会职责
- 中国类风湿关节炎诊疗指南(2024版)解读
- 《社会治理概论》课程教学大纲
- 读书分享《非暴力沟通》课件(图文)
- 钳工实训安全
- 通信施工安全培训
- 智慧生活:AI与智能家居-揭秘未来智能化生活趋势
- 消渴症护理查房
- 《钢铁是怎样炼成的》读书分享课件
- DB11T 2120-2023 古建筑安全防范技术规范
- 2023年银行安全保卫考试真题模拟汇编(共392题)
- DB34T 4627-2023 人民防空工程防护质量检测技术规程
评论
0/150
提交评论