ConcurrencyI:ThreadsApril10,2001Topics• Threadconcept• Posixthreads(Pthreads)interface• Linux Pthreads implementation• Concurrentexecution• Sharingdataclass22.ppt15-213“ThecoursethatgivesCMUitsZip!”CS213S’01– 2–class22.pptTraditionalviewofaprocesssharedlibrariesrun-timeheap0read/writedataProcess=processcontext+code,data,andstackProgramcontext:DataregistersConditioncodesStackpointer(SP)Programcounter(PC)Kernelcontext:VMstructuresOpenfilesSignalhandlersbrkpointerCode,data,andstackread-onlycode/datastackSPPCbrkProcesscontextCS213S’01– 3–class22.pptModernviewofaprocesssharedlibrariesrun-timeheap0read/writedataProcess=thread+code,data,andkernelcontextThreadcontext:DataregistersConditioncodesStackpointer(SP)Programcounter(PC)CodeandDataread-onlycode/datastackSPPCbrkThread(mainthread)Kernelcontext:VMstructuresOpenfilesSignalhandlersbrk pointerCS213S’01– 4–class22.pptAprocesswithmultiplethreadssharedlibrariesrun-timeheap0read/writedataThread1context:DataregistersConditioncodesSP1PC1Sharedcodeanddataread-onlycode/datastack1Thread1(mainthread)Kernelcontext:VMstructuresOpenfilesSignalhandlersbrk pointerMultiplethreadscanbeassociatedwithaprocess• Eachthreadhasitsownlogicalcontrolflow(sequenceofPCvalues)• Eachthreadhasitsownstack• Eachthreadsharesthesamecode,data,andkernelcontext• Eachthreadhasitsownthreadid(tid)Thread2context:DataregistersConditioncodesSP2PC2stack2Thread2(peerthread)CS213S’01– 5–class22.pptLogicalviewofthreadsThreadsassociatedwithaprocessformapoolofpeers.• unlikeprocesseswhichformatreehierarchyP0P1sh sh shfoobarT1ProcesshierarchyThreadsassociatedwithprocessfooT2T4T5T3sharedcode,dataandkernelcontextCS213S’01– 6–class22.pptConcurrentthreadexecutionTwothreadsrunconcurrently (areconcurrent) iftheirlogicalflowsoverlapintime.Otherwise,theyaresequential.Examples:• Concurrent:A&B,A&C• Sequential:B&CTimeThreadA ThreadB ThreadCCS213S’01– 7–class22.pptThreadsvsprocessesHowthreadsandprocessesaresimilar• Eachhasitsownlogicalcontrolflow.• Eachcanrunconcurrently.• Eachiscontextswitched.Howthreadsandprocessesaredifferent• Threadssharecodeanddata,processes(typically)donot.• Threadsaresomewhatlessexpensivethanprocesses.–processcontrol(creatingandreaping)istwiceasexpensiveasthreadcontrol.–Linux/PentiumIIInumbers:»20Kcyclestocreateandreapaprocess.»10Kcyclestocreateandreapathread.CS213S’01– 8–class22.pptThreadsareaunifyingabstractionforexceptionalcontrolflowExceptionhandler• Ahandlercanbeviewedasathread• Waitsfora"signal"fromCPU• Uponreceipt,executessomecode,thenwaitsfornext"signal"Process• Aprocessisathread+sharedcode,data,andkernelcontext.Signalhandler• Asignalhandlercanbeviewedasathread• Waitsforasignalfromthekerneloranotherprocess• Uponreceipt,executessomecode,thenwaitsfornextsignal.CS213S’01– 9–class22.pptPosixthreads(Pthreads)interfacePthreads: Standardinterfacefor~60functionsthatmanipulatethreadsfromCprograms.• Creatingandreapingthreads.–pthread_create–pthread_join•DeterminingyourthreadID–pthread_self•Terminatingthreads–pthread_cancel–pthread_exit–exit() [terminatesallthreads],ret[terminatescurrentthread]• Synchronizingaccesstosharedvariables–pthread_mutex_init–pthread_mutex_[un]lock–pthread_cond_init–pthread_cond_[timed]waitCS213S’01– 10–class22.pptThePthreads"hello,world"program/**hello.c- Pthreads "hello,world"program*/#include<ics.h>void*thread(void*vargp);int main(){pthread_t tid;Pthread_create(&tid,NULL,thread,NULL);Pthread_join(tid,NULL);exit(0);}/*threadroutine*/void*thread(void*vargp){printf("Hello,world!\n");returnNULL;}Threadattributes(usuallyNULL)Threadarguments(void*p)returnvalue(void**p)CS213S’01– 11–class22.pptExecutionof“hello,world”mainthread peerthreadcreatepeerthreadprintoutputterminatethreadviaretwaitforpeerthreadtoterminateexit() terminatesmainthreadandanypeerthreadsCS213S’01– 12–class22.pptUnixvsPosix errorhandlingUnix-styleerrorhandling(Unixsyscalls)• iferror:return-1andseterrno variabletoerrorcode.• ifOK:returnusefulresultasvalue>=0.Posix-styleerrorhandling(newerPosix functions)• iferror:returnnonzeroerrorcode,zeroifOK• usefulresultsarepassedbackinanargument.if((pid =wait(NULL))<0){perror("wait");exit(0);}if((rc= pthread_join(tid,&retvalp))!=0){printf(”pthread_create:%s\n",strerror(rc));exit(0);}CS213S’01– 13–class22.pptSuggestederrorhandlingmacrosErrorcheckingcrucial,butcluttered.Usethesetosimplifyyourerrorchecking:/**macrofor posix-styleerrorhandling*/#define posix_error(code,msg)do{\printf("%s:%s\n", msg, strerror(code));\exit(0);\}while(0)/**macrofor unix-styleerrorhandling*/#define unix_error(msg)do{\printf("%s:%s\n", msg, strerror(errno));\exit(0);\}while(0)CS213S’01–
View Full Document