PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) NAME pth−GNUPortableThreads VERSION GNUPthPTHVERSIONSTR SYNOPSIS GlobalLibraryManagement pthinit,pthkill,pthctrl,pthversion. ThreadAttributeHandling pthattrof,pthattrnew,pthattrinit,pthattrset,pthattrget,pthattrdestroy. ThreadControl pthspawn,pthonce,pthself,pthsuspend,pthresume,pthyield,pthnap,pthwait, pthcancel,pthabort,pthraise,pthjoin,pthexit. Utilities pthfdmode,pthtime,pthtimeout,pthsfiodisc. CancellationManagement pthcancelpoint,pthcancelstate. EventHandling pthevent,ptheventtypeof,ptheventextract,ptheventconcat,ptheventisolate, ptheventwalk,ptheventstatus,ptheventfree. Key-BasedStorage pthkeycreate,pthkeydelete,pthkeysetdata,pthkeygetdata. MessagePortCommunication pthmsgportcreate,pthmsgportdestroy,pthmsgportfind,pthmsgportpending, pthmsgportput,pthmsgportget,pthmsgportreply. ThreadCleanups pthcleanuppush,pthcleanuppop. ProcessForking pthatforkpush,pthatforkpop,pthfork. Synchronization pthmutexinit,pthmutexacquire,pthmutexrelease,pthrwlockinit,pthrwlockacquire, pthrwlockrelease,pthcondinit,pthcondawait,pthcondnotify,pthbarrierinit, pthbarrierreach. User-SpaceContext pthuctxcreate,pthuctxmake,pthuctxswitch,pthuctxdestroy. GeneralizedPOSIXReplacementAPI pthsigwaitev,pthacceptev,pthconnectev,pthselectev,pthpollev,pthreadev, pthreadvev,pthwriteev,pthwritevev,pthrecvev,pthrecvfromev,pthsendev, pthsendtoev. StandardPOSIXReplacementAPI pthnanosleep,pthusleep,pthsleep,pthwaitpid,pthsystem,pthsigmask,pthsigwait, pthaccept,pthconnect,pthselect,pthpselect,pthpoll,pthread,pthreadv,pthwrite, pthwritev,pthpread,pthpwrite,pthrecv,pthrecvfrom,pthsend,pthsendto. DESCRIPTION perlv5.8.6 2004-12-03 1 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

______
|_\||_||__
||_)|__|'_\``Onlythosewhoattempt
|__/||_||||theabsurdcanachieve
|_|\__|_||_|theimpossible.''

PthisaveryportablePOSIX/ANSI−CbasedlibraryforUnixplatformswhichprovidesnon-pre-emptivepriority-basedschedulingformultiplethreadsofexecution(aka‘multithreading’)inside event-drivenapplications.Allthreadsruninthesameaddressspaceoftheapplicationprocess, buteachthreadhasitsownindividualprogramcounter,run-timestack,signalmaskanderrno variable. Thethreadschedulingitselfisdoneinacooperativeway,i.e.,thethreadsaremanagedanddispatchedbyapriority−andevent-drivennon-preemptivescheduler.Theintentionisthatthisway bothbetterportabilityandrun-timeperformanceisachievedthanwithpreemptivescheduling. Theeventfacilityallowsthreadstowaituntilvarioustypesofinternalandexternaleventsoccur, includingpendingI/Oonfiledescriptors,asynchronoussignals,elapsedtimers,pendingI/Oon messageports,threadandprocesstermination,andevenresultsofcustomizedcallbackfunctions. PthalsoprovidesanoptionalemulationAPIforPOSIX.1cthreads(‘Pthreads’)whichcanbeused forbackwardcompatibilitytoexistingmultithreadedapplications.SeePth’spthread(3)manual pagefordetails. ThreadingBackground Whenprogrammingevent-drivenapplications,usuallyservers,lotsofregularjobsandone-shot requestshavetobeprocessedinparallel.Toefficientlysimulatethisparallelprocessingon uniprocessormachines,weuse‘multitasking’—thatis,wehavetheapplicationasktheoperating systemtospawnmultipleinstancesofitself.OnUnix,typicallythekernelimplementsmultitaskinginapreemptiveandpriority-basedwaythroughheavy-weightprocessesspawnedwithfork(2). Theseprocessesusuallydonotshareacommonaddressspace.Insteadtheyareclearlyseparated fromeachother,andarecreatedbydirectcloningaprocessaddressspace(althoughmodernkernelsusememorysegmentmappingandcopy-on-writesemanticstoavoidunnecessarycopyingof physicalmemory). Thedrawbacksareobvious:Sharingdatabetweentheprocessesiscomplicated,andcanusually onlybedoneefficientlythroughsharedmemory(butwhichitselfisnotveryportable).SynchronizationiscomplicatedbecauseofthepreemptivenatureoftheUnixscheduler(onehastouse atomiclocks,etc).Themachine’sresourcescanbeexhaustedveryquicklywhentheserverapplicationhastoservetoomanylong-runningrequests(heavy−weightprocessescostmemory).And wheneachrequestspawnsasub-processtohandleit,theserverperformanceandresponsivenessis horrible(heavy−weightprocessescosttimetospawn).Finally,theserverapplicationdoesn’tscale verywellwiththeloadbecauseoftheseresourceproblems.Inpractice,lotsoftricksareusually usedtoovercometheseproblems−rangingfrompre-forkedsub-processpoolstosemi-serialized processing,etc. Oneofthemostelegantwaystosolvetheseresource−anddata-sharingproblemsistohavemulti-plelight-weightthreadsofexecutioninsideasingle(heavy−weight)process,i.e.,tousemulti-threading.Thosethreadsusuallyimproveresponsivenessandperformanceoftheapplication,often improveandsimplifytheinternalprogramstructure,andmostimportant,requirelesssystem resourcesthanheavy-weightprocesses.Threadsareneithertheoptimalrun-timefacilityforall typesofapplications,norcanallapplicationsbenefitfromthem.Butatleastevent-drivenserver applicationsusuallybenefitgreatlyfromusingthreads. perlv5.8.6 2004-12-03 2 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) TheWorldofThreading Eventhoughlotsofdocumentsexistswhichdescribeanddefinetheworldofthreading,tounderstandPth,youneedonlybasicknowledgeaboutthreading.Thefollowingdefinitionsofthreadrelatedtermsshouldatleasthelpyouunderstandthreadprogrammingenoughtoallowyoutouse Pth. oprocessvs.thread AprocessonUnixsystemsconsistsofatleastthefollowingfundamentalingredients:virtual memorytable,programcode,programcounter,heapmemory,stackmemory,stackpointer,file descriptorset,signaltable.Oneveryprocessswitch,thekernelsavesandrestorestheseingredientsfortheindividualprocesses.Ontheotherhand,athreadconsistsofonlyaprivateprogram counter,stackmemory,stackpointerandsignaltable.Allotheringredients,inparticularthe virtualmemory,itshareswiththeotherthreadsofthesameprocess. okernel-spacevs.user-spacethreading ThreadsonaUnixplatformtraditionallycanbeimplementedeitherinsidekernel-spaceor user−space.Whenthreadsareimplementedbythekernel,thethreadcontextswitchesareperformedbythekernelwithouttheapplication’sknowledge.Similarly,whenthreadsareimplementedinuser−space,thethreadcontextswitchesareperformedbyanapplicationlibrary, withoutthekernel’sknowledge.Therealsoarehybridthreadingapproacheswhere,typically,a user-spacelibrarybindsoneormoreuser-spacethreadstooneormorekernel-spacethreads (thereusuallycalledlight-weightprocesses−orinshortLWPs). User-spacethreadsareusuallymoreportableandcanperformfasterandcheapercontext switches(forinstanceviaswapcontext(2)orsetjmp(3)/longjmp(3))thankernelbasedthreads. Ontheotherhand,kernel-spacethreadscantakeadvantageofmultiprocessormachinesand don’thaveanyinherentI/Oblockingproblems.Kernel-spacethreadsareusuallyscheduledin preemptivewayside-by-sidewiththeunderlyingprocesses.User-spacethreadsontheother handuseeitherpreemptiveornon-preemptivescheduling. opreemptivevs.non-preemptivethreadscheduling Inpreemptivescheduling,theschedulerletsathreadexecuteuntilablockingsituationoccurs (usuallyafunctioncallwhichwouldblock)ortheassignedtimesliceelapses.Thenitdetracts controlfromthethreadwithoutachanceforthethreadtoobject.Thisisusuallyrealizedby interruptingthethreadthroughahardwareinterruptsignal(forkernel-spacethreads)orasoft-wareinterruptsignal(foruser-spacethreads),likeSIGALRMorSIGVTALRM.Innon-preemptive scheduling,onceathreadreceivedcontrolfromthescheduleritkeepsituntileitherablocking situationoccurs(againafunctioncallwhichwouldblockandinsteadswitchesbacktothe scheduler)orthethreadexplicitlyyieldscontrolbacktotheschedulerinacooperativeway. oconcurrencyvs.parallelism Concurrencyexistswhenatleasttwothreadsareinprogressatthesametime.Parallelism ariseswhenatleasttwothreadsareexecutingsimultaneously.Realparallelismcanbeonly achievedonmultiprocessormachines,ofcourse.Butonealsousuallyspeaksofparallelismor highconcurrencyinthecontextofpreemptivethreadschedulingandoflowconcurrencyinthe contextofnon-preemptivethreadscheduling. oresponsiveness Theresponsivenessofasystemcanbedescribedbytheuservisibledelayuntilthesystem responsestoanexternalrequest.Whenthisdelayissmallenoughandtheuserdoesn’trecognizeanoticeabledelay,theresponsivenessofthesystemisconsideredgood.Whentheuserrecognizesorisevenannoyedbythedelay,theresponsivenessofthesystemisconsideredbad. oreentrant,thread-safeandasynchronous-safefunctions Areentrantfunctionisonethatbehavescorrectlyifitiscalledsimultaneouslybyseveral threadsandthenalsoexecutessimultaneously.Functionsthataccessglobalstate,suchas memoryorfiles,ofcourse,needtobecarefullydesignedinordertobereentrant.Twotraditionalapproachestosolvetheseproblemsarecaller-suppliedstatesandthread-specificdata. perlv5.8.6 2004-12-03 3 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) Thread-safetyistheavoidanceofdataraces,i.e.,situationsinwhichdataissettoeithercorrect orincorrectvaluedependinguponthe(unpredictable)orderinwhichmultiplethreadsaccess andmodifythedata.Soafunctionisthread-safewhenitstillbehavessemanticallycorrect whencalledsimultaneouslybyseveralthreads(itisnotrequiredthatthefunctionsalsoexecute simultaneously).Thetraditionalapproachtoachievethread-safetyistowrapafunctionbody withaninternalmutualexclusionlock(aka‘mutex’).Asyoushouldrecognize,reentrantisa strongerattributethanthread−safe,becauseitishardertoachieveandresultsespeciallyinno run-timecontentionbetweenthreads.So,areentrantfunctionisalwaysthread−safe,butnot viceversa. Additionallythereisarelatedattributeforfunctionsnamedasynchronous−safe,whichcomes intoplayinconjunctionwithsignalhandlers.Thisisveryrelatedtotheproblemofreentrant functions.Anasynchronous-safefunctionisonethatcanbecalledsafeandwithoutside-effects fromwithinasignalhandlercontext.Usuallyveryfewfunctionsareofthistype,becausean applicationisveryrestrictedinwhatitcanperformfromwithinasignalhandler(especially whatsystemfunctionsitisallowedtocall).Thereasonmainlyis,becauseonlyafewsystem functionsareofficiallydeclaredbyPOSIXasguaranteedtobeasynchronous−safe.Asynchronous-safefunctionsusuallyhavetobealreadyreentrant. User-SpaceThreads User-spacethreadscanbeimplementedinvariousway.Thetwotraditionalapproachesare: 1.Matrix-basedexplicitdispatchingbetweensmallunitsofexecution: Heretheglobalproceduresoftheapplicationaresplitintosmallexecutionunits(eachis requiredtonotrunformorethanafewmilliseconds)andthoseunitsareimplementedbyseparatefunctions.Thenaglobalmatrixisdefinedwhichdescribestheexecution(andperhaps evendependency)orderofthesefunctions.Themainserverprocedurethenjustdispatches betweentheseunitsbycallingonefunctionaftereachothercontrolledbythismatrix.The threadsarecreatedbymorethanonejump-trailthroughthismatrixandbyswitchingbetween thesejump-trailscontrolledbycorrespondingoccurredevents. Thisapproachgivesthebestpossibleperformance,becauseonecanfine-tunethethreadsof executionbyadjustingthematrix,andtheschedulingisdoneexplicitlybytheapplication itself.Itisalsoveryportable,becausethematrixisjustanordinarydatastructure,andfunctionsareastandardfeatureofANSIC. Thedisadvantageofthisapproachisthatitiscomplicatedtowritelargeapplicationswiththis approach,becauseinthoseapplicationsonequicklygetshundreds(!)ofexecutionunitsandthe controlflowinsidesuchanapplicationisveryhardtounderstand(becauseitisinterruptedby functionbordersandonealwayshastoremembertheglobaldispatchingmatrixtofollowit). Additionally,allthreadsoperateonthesameexecutionstack.Althoughthissavesmemory,it isoftennasty,becauseonecannotswitchbetweenthreadsinthemiddleofafunction.Thus theschedulingbordersarethefunctionborders. 2.Context-basedimplicitschedulingbetweenthreadsofexecution: Heretheideaisthatoneprogramstheapplicationaswithforkedprocesses,i.e.,onespawnsa threadofexecutionandthisrunsfromthebegintotheendwithoutaninterruptedcontrol flow.Butthecontrolflowcanbestillinterrupted−eveninthemiddleofafunction.Actually inapreemptiveway,similartowhatthekerneldoesfortheheavy-weightprocesses,i.e.,every fewmillisecondstheuser-spaceschedulerswitchesbetweenthethreadsofexecution.Butthe threaditselfdoesn’trecognizethisandusually(exceptforsynchronizationissues)doesn’thave tocareaboutthis. Theadvantageofthisapproachisthatit’sveryeasytoprogram,becausethecontrolflowand contextofathreaddirectlyfollowsaprocedurewithoutforcedinterruptsthroughfunction borders.Additionally,theprogrammingisverysimilartoatraditionalandwellunderstood perlv5.8.6 2004-12-03 4 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) fork(2)basedapproach. Thedisadvantageisthatalthoughthegeneralperformanceisincreased,comparedtousing approachesbasedonheavy-weightprocesses,itisdecreasedcomparedtothematrix-approach above.Becausetheimplicitpreemptiveschedulingdoesusuallyalotmorecontextswitches (everyuser-spacecontextswitchcostssomeoverheadevenwhenitisalotcheaperthanaker-nel-levelcontextswitch)thantheexplicitcooperative/non−preemptivescheduling.Finally, thereisnoreallyportablePOSIX/ANSI−Cbasedwaytoimplementuser-spacepreemptive threading.Eithertheplatformalreadyhasthreads,oronehastohopethatsomesemi-porta-blepackageexistsforit.Andeventhosesemi-portablepackagesusuallyhavetodealwith assemblercodeandothernastyinternalsandarenoteasytoporttoforthcomingplatforms. So,inshort:thematrix-dispatchingapproachisportableandfast,butnastytoprogram.The threadschedulingapproachiseasytoprogram,butsuffersfromsynchronizationandportability problemscausedbyitspreemptivenature. TheCompromiseofPth Butwhynotcombinethegoodaspectsofbothapproacheswhileavoidingtheirbadaspects? That’sthegoalofPth.Pthimplementseasy-to-programthreadsofexecution,butavoidsthe problemsofpreemptiveschedulingbyusingnon-preemptiveschedulinginstead. Thissoundslike,andis,ausefulapproach.Nevertheless,onehastokeeptheimplicationsofnonpreemptivethreadschedulinginmindwhenworkingwithPth.Thefollowinglistsummarizesa fewessentialpoints: o Pthprovidesmaximumportability,butNOTthefanciestfeatures. Thisis,becauseitusesaniftyandportablePOSIX/ANSI−Capproachforthreadcreation(and thiswaydoesn’trequireanyplatformdependentassemblerhacks)andschedulesthethreadsin non-preemptiveway(whichdoesn’trequireunportablefacilitieslikeSIGVTALRM).Ontheother hand,thiswaynotallfancythreadingfeaturescanbeimplemented.Neverthelesstheavailable facilitiesareenoughtoprovidearobustandfull-featuredthreadingsystem. o Pthincreasestheresponsivenessandconcurrencyofanevent-drivenapplication, butNOTtheconcurrencyofnumber-crunchingapplications. Thereasonisthenon-preemptivescheduling.Number-crunchingapplicationsusuallyrequire preemptiveschedulingtoachieveconcurrencybecauseoftheirlongCPUbursts.Forthem,nonpreemptivescheduling(eventogetherwithexplicityielding)providesonlytheoldconceptof ‘coroutines’.Ontheotherhand,eventdrivenapplicationsbenefitgreatlyfromnon-preemptive scheduling.TheyhaveonlyshortCPUburstsandlotsofeventstowaiton,andthiswayrun fasterundernon-preemptiveschedulingbecausenounnecessarycontextswitchingoccurs,asit isthecaseforpreemptivescheduling.That’swhyPthismainlyintendedforservertypeapplications,althoughthereisnotechnicalrestriction. o Pthrequiresthread-safefunctions,butNOTreentrantfunctions. Thisnicefactexistsagainbecauseofthenatureofnon-preemptivescheduling,whereafunction isn’tinterruptedandthiswaycannotbereenteredbeforeitreturned.Thisisagreatportability benefit,becausethread-safetycanbeachievedmoreeasilythanreentrancepossibility.Espe-ciallythismeansthatunderPthmoreexistingthird-partylibrariescanbeusedwithoutside-effectsthanit’sthecaseforotherthreadingsystems. o Pthdoesn’trequireanykernelsupport,butcanNOTbenefitfrommultiprocessor machines. perlv5.8.6 2004-12-03 5 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) ThismeansthatPthrunsonalmostallUnixkernels,becausethekerneldoesnotneedtobe awareofthePththreads(becausetheyareimplementedentirelyinuser−space).Ontheother hand,itcannotbenefitfromtheexistenceofmultiprocessors,becauseforthis,kernelsupport wouldbeneeded.Inpractice,thisisnoproblem,becausemultiprocessorsystemsarerare,and portabilityisalmostmoreimportantthanhighestconcurrency. Thelifecycleofathread TounderstandthePthApplicationProgrammingInterface(API),ithelpstofirstunderstandthe lifecycleofathreadinthePththreadingsystem.Itcanbeillustratedwiththefollowingdirected graph:

NEW

|

V
+--->READY---+

|^| ||V

WAITING<--+--RUNNING

|

:V
SUSPENDEDDEAD

Whenanewthreadiscreated,itismovedintotheNEWqueueofthescheduler.Onthenextdispatchingforthisthread,theschedulerpicksitupfromthereandmovesittotheREADYqueue. ThisisaqueuecontainingallthreadswhichwanttoperformaCPUburst.Theretheyarequeued inpriorityorder.Oneachdispatchingstep,thescheduleralwaysremovesthethreadwiththe highestpriorityonly.Itthenincreasesthepriorityofallremainingthreadsby1,topreventthem from‘starving’. ThethreadwhichwasremovedfromtheREADYqueueisthenewRUNNINGthread(thereis alwaysjustoneRUNNINGthread,ofcourse).TheRUNNINGthreadisassignedexecutioncontrol.Afterthisthreadyieldsexecution(eitherexplicitlybyyieldingexecutionorimplicitlybycallingafunctionwhichwouldblock)therearethreepossibilities:Eitherithasterminated,thenitis movedtotheDEADqueue,orithaseventsonwhichitwantstowait,thenitismovedintothe WAITINGqueue.ElseitisassumeditwantstoperformmoreCPUburstsandimmediatelyenters theREADYqueueagain. BeforethenextthreadistakenoutoftheREADYqueue,theWAITINGqueueischeckedfor pendingevents.Ifoneormoreeventsoccurred,thethreadsthatarewaitingonthemareimmediatelymovedtotheREADYqueue. ThepurposeoftheNEWqueuehastodowiththefactthatinPthathreadneverdirectly switchestoanotherthread.Athreadalwaysyieldsexecutiontotheschedulerandthescheduler dispatchestothenextthread.Soafreshlyspawnedthreadhastobekeptsomewhereuntilthe schedulergetsachancetopickitupforscheduling.ThatiswhattheNEWqueueisfor. ThepurposeoftheDEADqueueistosupportthreadjoining.Whenathreadismarkedtobe unjoinable,itisdirectlykickedoutofthesystemafteritterminated.Butwhenitisjoinable,it enterstheDEADqueue.Thereitremainsuntilanotherthreadjoinsit. Finally,thereisaspecialseparatedqueuenamedSUSPENDED,towherethreadscanbemanuallymovedfromtheNEW,READYorWAITINGqueuesbytheapplication.Thepurposeofthis specialqueueistotemporarilyabsorbsuspendedthreadsuntiltheyareagainresumedbythe application.Suspendedthreadsdonotcostschedulingoreventhandlingresources,becausethey aretemporarilycompletelyoutofthescheduler’sscope.Ifathreadisresumed,itismovedback tothequeuefromwhereitoriginallycameandthiswayagainenterstheschedulersscope. perlv5.8.6 2004-12-03 6 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) APPLICATIONPROGRAMMINGINTERFACE(API) InthefollowingthePthApplicationProgrammingInterface(API)isdiscussedindetail.Withthe knowledgegivenabove,itshouldnowbeeasytounderstandhowtoprogramthreadswiththis API.IngoodUnixtradition,Pthfunctionsusespecialreturnvalues(NULLinpointercontext, FALSEinbooleancontextand-1inintegercontext)toindicateanerrorconditionandset(orpass through)theerrnosystemvariabletopassmoredetailsabouttheerrortothecaller. GlobalLibraryManagement Thefollowingfunctionsactonthelibraryasawhole.Theyareusedtoinitializeandshutdown theschedulerandfetchinformationfromit. intpthinit(void); ThisinitializesthePthlibrary.IthastobethefirstPthAPIfunctioncallinanapplication, andismandatory.It’susuallydoneatthebeginofthemain()functionoftheapplication. Thisimplicitlyspawnstheinternalschedulerthreadandtransformsthesingleexecutionunit ofthecurrentprocessintoathread(the‘main’thread).ItreturnsTRUEonsuccessandFALSE onerror. intpthkill(void); ThiskillsthePthlibrary.ItshouldbethelastPthAPIfunctioncallinanapplication,but isnotreallyrequired.It’susuallydoneattheendofthemainfunctionoftheapplication.At least,ithastobecalledfromwithinthemainthread.Itimplicitlykillsallthreadsandtransformsbackthecallingthreadintothesingleexecutionunitoftheunderlyingprocess.The usualwaytoterminateaPthapplicationiseitherasimple‘pth_exit(0);’inthemain thread(whichwaitsforallotherthreadstoterminate,killsthethreadingsystemandthen terminatestheprocess)ora‘pth_kill();exit(0)’(whichimmediatelykillsthethreading systemandterminatestheprocess).Thepthkill()returnimmediatelywithareturncodeof FALSEifitisnotcalledfromwithinthemainthread.Elseitkillsthethreadingsystemand returnsTRUE. longpthctrl(unsignedlongquery,...); Thisisageneralizedquery/controlfunctionforthePthlibrary.Theargumentqueryisa bitmaskformedoutofoneormorePTH_CTRL_XXXXqueries.Currentlythefollowingqueries aresupported:

PTH_CTRL_GETTHREADS

Thisreturnsthetotalnumberofthreadscurrentlyinexistence.Thisqueryactuallyis formedoutofthecombinationofqueriesforthreadsinaparticularstate,i.e.,the PTH_CTRL_GETTHREADSqueryisequaltotheOR-combinationofallthefollowingspecial-izedqueries: PTH_CTRL_GETTHREADS_NEWforthenumberofthreadsinthenewqueue(threadscreated viapthspawn(3)butstillnotscheduledonce),PTH_CTRL_GETTHREADS_READYforthe numberofthreadsinthereadyqueue(threadswhowanttodoCPUbursts), PTH_CTRL_GETTHREADS_RUNNINGforthenumberofrunningthreads(alwaysjustone thread!),PTH_CTRL_GETTHREADS_WAITINGforthenumberofthreadsinthewaitingqueue (threadswaitingforevents),PTH_CTRL_GETTHREADS_SUSPENDEDforthenumberof threadsinthesuspendedqueue(threadswaitingtoberesumed)and PTH_CTRL_GETTHREADS_DEADforthenumberofthreadsinthenewqueue(terminated threadswaitingforajoin).

PTH_CTRL_GETAVLOAD

Thisrequiresasecondargumentoftype‘float*’(pointertoafloatingpointvariable). Itstoresafloatingpointvaluedescribingtheexponentialaveragedloadofthescheduler inthisvariable.Theloadisafunctionfromthenumberofthreadsinthereadyqueueof theschedulersdispatchingunit.Soaloadaround1.0meansthereisonlyoneready thread(thestandardsituationwhentheapplicationhasnohighload).Ahigherload valuemeansthereamorethreadsreadywhowanttodoCPUbursts.Theaverageload perlv5.8.6 2004-12-03 7 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) valueupdatesoncepersecondonly.Thereturnvalueforthisqueryisalways0.

PTH_CTRL_GETPRIO

Thisrequiresasecondargumentoftype‘pth_t’whichidentifiesathread.Itreturnsthe priority(rangingfromPTH_PRIO_MINtoPTH_PRIO_MAX)ofthegiventhread.

PTH_CTRL_GETNAME

Thisrequiresasecondargumentoftype‘pth_t’whichidentifiesathread.Itreturnsthe nameofthegiventhread,i.e.,thereturnvalueofpthctrl(3)shouldbecastedtoa‘char *’.

PTH_CTRL_DUMPSTATE

Thisrequiresasecondargumentoftype‘FILE*’towhichasummaryoftheinternal Pthlibrarystateiswrittento.Themaininformationwhichiscurrentlywrittenoutis thecurrentstateofthethreadpool.

PTH_CTRL_FAVOURNEW

Thisrequiresasecondargumentoftype‘int’whichspecifiedwhethertheGNUPth schedulerfavoursnewthreadsonstartup,i.e.,whethertheyaremovedfromthenew queuetothetop(argumentisTRUE)ormiddle(argumentisFALSE)ofthereadyqueue. Thedefaultistofavournewthreadstomakesuretheydonotstarvealreadyatstartup, althoughthisslightlyviolatesthestrictprioritybasedscheduling. Thefunctionreturns-1onerror. longpthversion(void); Thisfunctionreturnsahex-value‘0xVRRTLL’whichdescribesthecurrentPthlibraryver-sion.Vistheversion,RRtherevisions,LLthelevelandTthetypeofthelevel (alphalevel=0,betalevel=1,patchlevel=2,etc).ForinstancePthversion1.0b1isencodedas 0x100101.Thereasonforthisunusualmappingisthatthiswaytheversionnumberis steadilyincreasing.ThesamevalueisalsoavailableundercompiletimeasPTH_VERSION. ThreadAttributeHandling AttributeobjectsareusedinPthfortwothings:Firststand−alone/unboundattributeobjects areusedtostoreattributesfortobespawnedthreads.Boundedattributeobjectsareusedto modifyattributesofalreadyexistingthreads.Thefollowingattributefieldsexistsinattribute objects:

PTH_ATTR_PRIO(read−write)[int]

ThreadPrioritybetweenPTH_PRIO_MINandPTH_PRIO_MAX.ThedefaultisPTH_PRIO_STD.

PTH_ATTR_NAME(read−write)[char*]

Nameofthread(upto40charactersarestoredonly),mainlyfordebuggingpurposes.

PTH_ATTR_DISPATCHES(read−write)[int]

Inboundedattributeobjects,thisfieldisincrementedeverytimethecontextisswitchedto theassociatedthread.

PTH_ATTR_JOINABLE(read−write>[int]

Thethreaddetachmenttype,TRUEindicatesajoinablethread,FALSEindicatesadetached thread.Whenathreadisdetached,afterterminationitisimmediatelykickedoutofthesysteminsteadofinsertedintothedeadqueue.

PTH_ATTR_CANCEL_STATE(read−write)[unsignedint]

Thethreadcancellationstate,i.e.,acombinationofPTH_CANCEL_ENABLEor

PTH_CANCEL_DISABLEandPTH_CANCEL_DEFERREDorPTH_CANCEL_ASYNCHRONOUS.
PTH_ATTR_STACK_SIZE(read−write)[unsignedint]

Thethreadstacksizeinbytes.Uselowervaluesthan64KBwithgreatcare! perlv5.8.6 2004-12-03 8 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

PTH_ATTR_STACK_ADDR(read−write)[char*]

Apointertotheloweraddressofachunkofmalloc(3)’edmemoryforthestack.

PTH_ATTR_TIME_SPAWN(read−only)[pth_time_t]

Thetimewhenthethreadwasspawned.Thiscanbequeriedonlywhentheattributeobject isboundtoathread.

PTH_ATTR_TIME_LAST(read−only)[pth_time_t]

Thetimewhenthethreadwaslastdispatched.Thiscanbequeriedonlywhentheattribute objectisboundtoathread.

PTH_ATTR_TIME_RAN(read−only)[pth_time_t]

Thetotaltimethethreadwasrunning.Thiscanbequeriedonlywhentheattributeobjectis boundtoathread.

PTH_ATTR_START_FUNC(read−only)[void*(*)(void*)]

Thethreadstartfunction.Thiscanbequeriedonlywhentheattributeobjectisboundtoa thread.

PTH_ATTR_START_ARG(read−only)[void*]

Thethreadstartargument.Thiscanbequeriedonlywhentheattributeobjectisboundtoa thread.

PTH_ATTR_STATE(read−only)[pth_state_t]

Theschedulingstateofthethread,i.e.,eitherPTH_STATE_NEW,PTH_STATE_READY, PTH_STATE_WAITING,orPTH_STATE_DEADThiscanbequeriedonlywhentheattributeobject isboundtoathread.

PTH_ATTR_EVENTS(read−only)[pth_event_t]

Theeventringthethreadiswaitingfor.Thiscanbequeriedonlywhentheattributeobject isboundtoathread.

PTH_ATTR_BOUND(read−only)[int]

Whethertheattributeobjectisbound(TRUE)toathreadornot(FALSE). ThefollowingAPIfunctionscanbeusedtohandletheattributeobjects: pthattrtpthattrof(pthttid); Thisreturnsanewattributeobjectboundtothreadtid.Anyqueriesonthisobjectdirectly fetchattributesfromtid.Andattributemodificationsdirectlychangetid.Usesuchattribute objectstomodifyexistingthreads. pthattrtpthattrnew(void); Thisreturnsanewunboundattributeobject.Animplicitpthattrinit()isdoneonit.Any queriesonthisobjectjustfetchstoredattributesfromit.Andattributemodificationsjust changethestoredattributes.Usesuchattributeobjectstopre-configureattributesfortobe spawnedthreads. intpthattrinit(pthattrtattr); Thisinitializesanattributeobjectattrtothedefaultvalues:PTH_ATTR_PRIO:=

PTH_PRIO_STD,PTH_ATTR_NAME:=‘unknown’,PTH_ATTR_DISPATCHES:=0,
PTH_ATTR_JOINABLE:=TRUE,PTH_ATTR_CANCELSTATE:=PTH_CANCEL_DEFAULT,
PTH_ATTR_STACK_SIZE:=64*1024andPTH_ATTR_STACK_ADDR:=NULL.Allother

PTH_ATTR_*attributesareread-onlyattributesanddon’treceivedefaultvaluesinattr, becausetheyexistsonlyforboundedattributeobjects. intpthattrset(pthattrtattr,intfield,...); Thissetstheattributefieldfieldinattrtoavaluespecifiedasanadditionalargumentonthe variableargumentlist.Thefollowingattributefieldsandargumentpairscanbeused: perlv5.8.6 2004-12-03 9 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

PTH_ATTR_PRIOint
PTH_ATTR_NAMEchar*
PTH_ATTR_DISPATCHESint
PTH_ATTR_JOINABLEint
PTH_ATTR_CANCEL_STATEunsignedint
PTH_ATTR_STACK_SIZEunsignedint
PTH_ATTR_STACK_ADDRchar*

intpthattrget(pthattrtattr,intfield,...); Thisretrievestheattributefieldfieldinattrandstoresitsvalueinthevariablespecified throughapointerinanadditionalargumentonthevariableargumentlist.Thefollowing fieldsandargumentpairscanbeused:

PTH_ATTR_PRIOint*
PTH_ATTR_NAMEchar**
PTH_ATTR_DISPATCHESint*
PTH_ATTR_JOINABLEint*
PTH_ATTR_CANCEL_STATEunsignedint*
PTH_ATTR_STACK_SIZEunsignedint*
PTH_ATTR_STACK_ADDRchar**
PTH_ATTR_TIME_SPAWNpth_time_t*
PTH_ATTR_TIME_LASTpth_time_t*
PTH_ATTR_TIME_RANpth_time_t*
PTH_ATTR_START_FUNCvoid*(**)(void*)
PTH_ATTR_START_ARGvoid**
PTH_ATTR_STATEpth_state_t*
PTH_ATTR_EVENTSpth_event_t*
PTH_ATTR_BOUNDint*

intpthattrdestroy(pthattrtattr); Thisdestroysaattributeobjectattr.Afterthisattrisnolongeravalidattributeobject. ThreadControl ThefollowingfunctionscontrolthethreadingitselfandmakeupthemainAPIofthePthlibrary. pthtpthspawn(pthattrtattr,void*(*entry)(void*),void*arg); Thisspawnsanewthreadwiththeattributesgiveninattr(orPTH_ATTR_DEFAULTfordefault attributes−whichmeansthatthreadpriority,joinabilityandcancelstateareinheritedfrom thecurrentthread)withthestartingpointatroutineentry;thedispatchcountisnotinheritedfromthecurrentthreadifattrisnotspecified−rather,itisinitializedtozero.This entryroutineiscalledas‘pthexit(entry(arg))’insidethenewthreadunit,i.e.,entry’sreturn valueisfedtoanimplicitpthexit(3).Sothethreadcanalsoexitbyjustreturning.Neverthelessthethreadcanalsoexitexplicitlyatanytimebycallingpthexit(3).Butkeepinmind thatcallingthePOSIXfunctionexit(3)stillterminatesthecompleteprocessandnotjustthe currentthread. ThereisnoPth−internallimitonthenumberofthreadsonecanspawn,exceptthelimit impliedbytheavailablevirtualmemory.Pthinternallykeepstrackofthreadindynamic datastructures.ThefunctionreturnsNULLonerror. intpthonce(pthoncet*ctrlvar,void(*func)(void*),void*arg); Thisisaconveniencefunctionwhichusesacontrolvariableoftypepth_once_ttomakesure aconstructorfunctionfunciscalledonlyonceas‘func(arg)’inthesystem.Inotherwords: Onlythefirstcalltopthonce(3)byanythreadinthesystemsucceeds.Thevariablereferencedviactrlvarshouldbedeclaredas‘pth_once_tvariable-name=PTH_ONCE_INIT;’before callingthisfunction. perlv5.8.6 2004-12-03 10 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) pthtpthself(void); Thisjustreturnstheuniquethreadhandleofthecurrentlyrunningthread.Thishandleitself hastobetreatedasanopaqueentitybytheapplication.It’susuallyusedasanargumentto otherfunctionswhorequireanargumentoftypepth_t. intpthsuspend(pthttid); Thissuspendsathreadtiduntilitismanuallyresumedagainviapthresume(3).Forthis,the threadismovedtotheSUSPENDEDqueueandthiswayiscompletelyoutofthescheduler’s eventhandlingandthreaddispatchingscope.Suspendingthecurrentthreadisnotallowed. ThefunctionreturnsTRUEonsuccessandFALSEonerrors. intpthresume(pthttid); Thisfunctionresumesapreviouslysuspendedthreadtid,i.e.tidhastostayontheSUS-PENDEDqueue.ThethreadismovedtotheNEW,READYorWAITINGqueue(depen-dentonwhatitsstatewaswhenthepthsuspend(3)callweremade)andthiswayagain enterstheeventhandlingandthreaddispatchingscopeofthescheduler.Thefunctionreturns TRUEonsuccessandFALSEonerrors. intpthraise(pthttid,intsig) Thisfunctionraisesasignalfordeliverytothreadtidonly.Whenonejustraisesasignalvia raise(3)orkill(2),itsdeliveredtoanarbitrarythreadwhichhasthissignalnotblocked. Withpthraise(3)onecansendasignaltoathreadanditsguaranteesthatonlythisthread getsthesignaldelivered.Butkeepinmindthatneverthelessthesignalsactionisstillconfiguredprocess−wide.Whensigis0plainthreadcheckingisperformed,i.e.,‘pth_raise(tid, 0)’returnsTRUEwhenthreadtidstillexistsinthePTHsystembutdoesn’tsendanysignal toit. intpthyield(pthttid); Thisexplicitlyyieldsbacktheexecutioncontroltotheschedulerthread.Usuallytheexecutionisimplicitlytransferredbacktotheschedulerwhenathreadwaitsforanevent.But whenathreadhastodolargerCPUbursts,itcanbereasonabletointerruptitexplicitlyby doingafewpthyield(3)callstogiveotherthreadsachancetoexecute,too.Thisobviously isthecooperatingpartofPth.Athreadhasnottoyieldexecution,ofcourse.Butwhenyou wanttoprogramaserverapplicationwithgoodresponsetimesthethreadsshouldbecooperative,i.e.,whentheyshouldsplittheirCPUburstsintosmallerunitswiththiscall. UsuallyonespecifiestidasNULLtoindicatetotheschedulerthatitcanfreelydecidewhich threadtodispatchnext.Butifonewantstoindicatetotheschedulerthataparticular threadshouldbefavoredonthenextdispatchingstep,onecanspecifythisthreadexplicitly. Thisallowstheusageoftheoldconceptofcoroutineswhereathread/routineswitchestoa particularcooperatingthread.IftidisnotNULLandpointstoaneworreadythread,itis guaranteedthatthisthreadreceivesexecutioncontrolonthenextdispatchingstep.Iftidisin adifferentstate(thatis,notinPTH_STATE_NEWorPTH_STATE_READY)anerrorisreported. ThefunctionusuallyreturnsTRUEforsuccessandonlyFALSE(witherrnosettoEINVAL)if tidspecifiedaninvalidorstillnotneworreadythread. intpthnap(pthtimetnaptime); Thisfunctionssuspendstheexecutionofthecurrentthreaduntilnaptimeiselapsed.naptime isoftypepth_time_tandthiswayhastheoreticallyaresolutionofonemicrosecond.Inpracticeyoushouldneitherrelyonthisnorthatthethreadisawakenedexactlyafternaptimehas elapsed.It’sonlyguaranteesthatthethreadwillsleepatleastnaptime.Butbecauseofthe non-preemptivenatureofPthitcanlastlonger(whenanotherthreadkepttheCPUfora longtime).Additionallytheresolutionisdependentoftheimplementationoftimersbythe operatingsystemandtheseusuallyhaveonlyaresolutionof10microsecondsorlarger.But usuallythisisn’timportantforanapplicationunlessittriestousethisfacilityforrealtime tasks. perlv5.8.6 2004-12-03 11 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) intpthwait(ptheventtev); Thisisthelinkbetweentheschedulerandtheeventfacility(seebelowforthevarious ptheventxxx()functions).It’smodeledlikeselect(2),i.e.,onegivesthisfunctiononeor moreevents(intheeventringspecifiedbyev)onwhichthecurrentthreadwantstowait. Theschedulerawakesthethreadwhenoneoremoreofthemoccurredorfailedaftertagging themassuch.Theevargumentisapointertoaneventringwhichisn’tchangedexceptfor thetagging.pthwait(3)returnsthenumberofoccurredorfailedeventsandtheapplication canuseptheventstatus(3)totestwhicheventsoccurredorfailed. intpthcancel(pthttid); Thiscancelsathreadtid.Howthecancellationisdonedependsonthecancellationstateof tidwhichthethreadcanconfigureitself.WhenitsstateisPTH_CANCEL_DISABLEacancellationrequestisjustmadepending.WhenitisPTH_CANCEL_ENABLEitdependsonthecancellationtypewhatisperformed.WhenitsPTH_CANCEL_DEFERREDagainthecancellationrequest isjustmadepending.ButwhenitsPTH_CANCEL_ASYNCHRONOUSthethreadisimmediately canceledbeforepthcancel(3)returns.Theeffectofathreadcancellationisequaltoimplicitly forcingthethreadtocall‘pth_exit(PTH_CANCELED)’atoneofhiscancellationpoints.In Pththreadenteracancellationpointeitherexplicitlyviapthcancelpoint(3)orimplicitlyby waitingforanevent. intpthabort(pthttid); Thisisthecruelwaytocancelathreadtid.Whenit’salreadydeadandwaitstobejoinedit justjoinsit(via‘pth_join(tid,NULL)’)andthiswaykicksitoutofthesystem.Elseit forcesthethreadtobenotjoinableandtoallowasynchronouscancellationandthencancels

itvia‘pth_cancel(tid)’.

intpthjoin(pthttid,void**value); Thisjoinsthecurrentthreadwiththethreadspecifiedviatid.Itfirstsuspendsthecurrent threaduntilthetidthreadhasterminated.Thenitisawakenedandstoresthevalueoftid’s pthexit(3)callinto*value(ifvalueandnotNULL)andreturnstothecaller.Athreadcanbe joinedonlywhenithastheattributePTH_ATTR_JOINABLEsettoTRUE(thedefault).Athread canonlybejoinedonce,i.e.,afterthepthjoin(3)callthethreadtidiscompletelyremoved fromthesystem. voidpthexit(void*value); Thisterminatesthecurrentthread.Whetherit’simmediatelyremovedfromthesystemor insertedintothedeadqueueoftheschedulerdependsonitsjointypewhichwasspecifiedat spawningtime.IfithastheattributePTH_ATTR_JOINABLEsettoFALSE,it’simmediately removedandvalueisignored.Elsethethreadisinsertedintothedeadqueueandvalue rememberedforasubsequentpthjoin(3)callbyanotherthread. Utilities Utilityfunctions. intpthfdmode(intfd,intmode); Thisswitchesthenon-blockingmodeflagonfiledescriptorfd.Theargumentmodecanbe PTH_FDMODE_BLOCKforswitchingfdintoblockingI/Omode,PTH_FDMODE_NONBLOCKfor switchingfdintonon-blockingI/OmodeorPTH_FDMODE_POLLforjustpollingthecurrent mode.Thecurrentmodeisreturned(eitherPTH_FDMODE_BLOCKorPTH_FDMODE_NONBLOCK)or PTH_FDMODE_ERRORonerror.KeepinmindthatsincePth1.1thereisnolongerarequirementtomanuallyswitchafiledescriptorintonon-blockingmodeinordertouseit.Thisis automaticallydonetemporarilyinsidePth.Insteadwhenyounowswitchafiledescriptor explicitlyintonon-blockingmode,pthread(3)orpthwrite(3)willneverblockthecurrent thread. pthtimetpthtime(longsec,longusec); Thisisaconstructorforapth_time_tstructurewhichisaconvenientfunctiontoavoidtemporarystructurevalues.Itreturnsapthtimetstructurewhichholdstheabsolutetimevalue perlv5.8.6 2004-12-03 12 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) specifiedbysecandusec. pthtimetpthtimeout(longsec,longusec); Thisisaconstructorforapth_time_tstructurewhichisaconvenientfunctiontoavoidtemporarystructurevalues.Itreturnsapthtimetstructurewhichholdstheabsolutetime valuecalculatedbyaddingsecandusectothecurrenttime. Sfdisct*pthsfiodisc(void); Thisfunctionsisalwaysavailable,butonlyreasonablyusablewhenPthwasbuiltwithSfio support(--with-sfiooption)andPTH_EXT_SFIOisthendefinedbypth.h.Itisusefulfor applicationswhichwanttousethecomprehensiveSfioI/OlibrarywiththePththreading library.ThenthisfunctioncanbeusedtogetanSfiodisciplinestructure(Sfdisc_t)which canbepushedontoSfiostreams(Sfio_t)inordertoletthisstreamuse pthread(3)/pthwrite(2)insteadofread(2)/write(2).ThebenefitisthatthiswayI/Oonthe Sfiostreamdoesonlyblockthecurrentthreadinsteadofthewholeprocess.Theapplication hastofree(3)theSfdisc_tstructurewhenitisnolongerneeded.TheSfiopackagecanbe foundathttp://www.research.att.com/sw/tools/sfio/. CancellationManagement PthsupportsPOSIXstylethreadcancellationviapthcancel(3)andthefollowingtworelated functions: voidpthcancelstate(intnewstate,int*oldstate); Thismanagesthecancellationstateofthecurrentthread.WhenoldstateisnotNULLthe functionstorestheoldcancellationstateunderthevariablepointedtobyoldstate.When newstateisnot0itsetsthenewcancellationstate.oldstateiscreatedbeforenewstateisset.

AstateisacombinationofPTH_CANCEL_ENABLEorPTH_CANCEL_DISABLEand
PTH_CANCEL_DEFERREDorPTH_CANCEL_ASYNCHRONOUS.
PTH_CANCEL_ENABLE|PTH_CANCEL_DEFERRED(orPTH_CANCEL_DEFAULT)isthedefaultstate

wherecancellationispossiblebutonlyatcancellationpoints.UsePTH_CANCEL_DISABLEto completedisablecancellationforathreadandPTH_CANCEL_ASYNCHRONOUSforallowingasynchronouscancellations,i.e.,cancellationswhichcanhappenatanytime. voidpthcancelpoint(void); Thisexplicitlyenteracancellationpoint.Whenthecurrentcancellationstateis PTH_CANCEL_DISABLEornocancellationrequestispending,thishasnoside-effectandreturns immediately.Elseitcalls‘pth_exit(PTH_CANCELED)’. EventHandling Pthhasaveryflexibleeventfacilitywhichislinkedintotheschedulerthroughthepthwait(3) function.Thefollowingfunctionsprovidethehandlingofeventrings. ptheventtpthevent(unsignedlongspec,...); Thiscreatesaneweventringconsistingofasingleinitialevent.Thetypeofthegenerated eventisspecifiedbyspec.Thefollowingtypesareavailable:

PTH_EVENT_FD

Thisisafiledescriptorevent.OneormoreofPTH_UNTIL_FD_READABLE,

PTH_UNTIL_FD_WRITEABLEorPTH_UNTIL_FD_EXCEPTIONhavetobeOR-edintospecto

specifyonwhichstateofthefiledescriptoryouwanttowait.Thefiledescriptoritself hastobegivenasanadditionalargument.Example:

‘pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE,fd)’.
PTH_EVENT_SELECT

Thisisamultiplefiledescriptoreventmodeleddirectlyaftertheselect(2)call(actually itisalsousedtoimplementpthselect(3)internally).It’saconvenientwaytowaitfora largesetoffiledescriptorsatonceandateachfiledescriptorforadifferenttypeofstate. Additionallyasaniceside-effectonereceivesthenumberoffiledescriptorswhichcauses perlv5.8.6 2004-12-03 13 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) theeventtobeoccurred(usingBSDsemantics,i.e.,whenafiledescriptoroccurredin twosetsit’scountedtwice).Theargumentscorresponddirectlytotheselect(2)function argumentsexceptthatthereisnotimeoutargument(becausetimeoutsalreadycanbe handledviaPTH_EVENT_TIMEevents).

Example:‘pth_event(PTH_EVENT_SELECT,&rc,nfd,rfds,wfds,efds)’whererc

hastobeoftype‘int*’,nfdhastobeoftype‘int’andrfds,wfdsandefdshaveto beoftype‘fd_set*’(seeselect(2)).Thenumberofoccurredfiledescriptorsarestored inrc.

PTH_EVENT_SIGS

Thisisasignalsetevent.Thetwoadditionalargumentshavetobeapointertoasignal set(type‘sigset_t*’)andapointertoasignalnumbervariable(type‘int*’).This eventwaitsuntiloneofthesignalsinthesignalsetoccurred.Asaresulttheoccurred signalnumberisstoredinthesecondadditionalargument.KeepinmindthatthePth schedulerdoesn’tblocksignalsautomatically.Sowhenyouwanttowaitforasignal withthiseventyou’vetoblockitviasigprocmask(2)oritwillbedeliveredwithoutyour

notice.Example:‘sigemptyset(&set);sigaddset(&set,SIGINT);
pth_event(PTH_EVENT_SIG,&set,&sig);’.
PTH_EVENT_TIME

Thisisatimepointevent.Theadditionalargumenthastobeoftypepth_time_t(usuallyon-the-flygeneratedviapthtime(3)).Thiseventswaitsuntilthespecifiedtime pointhaselapsed.Keepinmindthatthevalueisanabsolutetimepointandnotanoffset.Whenyouwanttowaitforaspecifiedamountoftime,you’vetoaddthecurrent timetotheoffset(usuallyon-the-flyachievedviapthtimeout(3)).Example:

‘pth_event(PTH_EVENT_TIME,pth_timeout(2,0))’.
PTH_EVENT_MSG

Thisisamessageportevent.Theadditionalargumenthastobeoftypepth_msgport_t. Thiseventswaitsuntiloneormoremessageswerereceivedonthespecifiedmessageport.

Example:‘pth_event(PTH_EVENT_MSG,mp)’.
PTH_EVENT_TID

Thisisathreadevent.Theadditionalargumenthastobeoftypepth_t.Oneof

PTH_UNTIL_TID_NEW,PTH_UNTIL_TID_READY,PTH_UNTIL_TID_WAITINGor

PTH_UNTIL_TID_DEADhastobeOR-edintospectospecifyonwhichstateofthethread

youwanttowait.Example:‘pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD,tid)’.
PTH_EVENT_FUNC

Thisisacustomcallbackfunctionevent.Threeadditionalargumentshavetobegiven withthefollowingtypes:‘int(*)(void*)’,‘void*’and‘pth_time_t’.Thefirstisa functionpointertoacheckfunctionandthesecondargumentisauser-suppliedcontext valuewhichispassedtothisfunction.Theschedulercallsthisfunctiononaregularbasis (onhisownschedulerstack,sobeverycareful!)andthethreadiskeptsleepingwhilethe functionreturnsFALSE.OnceitreturnedTRUEthethreadwillbeawakened.Thecheck intervalisdefinedbythethirdargument,i.e.,thecheckfunctionispolledagainnotuntil

thisamountoftimeelapsed.Example:‘pth_event(PTH_EVENT_FUNC,func,arg,
pth_time(0,500000))’.

unsignedlongptheventtypeof(ptheventtev); Thisreturnsthetypeofeventev.It’sacombinationofthedescribingPTH_EVENT_XXand PTH_UNTIL_XXvalue.Thisisespeciallyusefultoknowwhichargumentshavetobesupplied totheptheventextract(3)function. intptheventextract(ptheventtev,...); Whenpthevent(3)istreatedlikesprintf(3),thenthisfunctionissscanf(3),i.e.,itisthe inverseoperationofpthevent(3).Thismeansthatitcanbeusedtoextracttheingredients ofanevent.Theingredientsarestoredintovariableswhicharegivenaspointersonthe perlv5.8.6 2004-12-03 14 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) variableargumentlist.Whichpointershavetobepresentdependsontheeventtypeandhas tobedeterminedbythecallerbeforeviaptheventtypeof(3). Tomakeitclear,whenyouconstructedevvia‘ev=pth_event(PTH_EVENT_FD,fd);’you havetoextractitvia‘pth_event_extract(ev,&fd)’,etc.Formultipleargumentsofan eventtheorderofthepointerargumentsisthesameasforpthevent(3).Butalwayskeepin mindthatyouhavetoalwayssupplypointerstovariablesandthesevariableshavetobeof thesametypeastheargumentofpthevent(3)required. ptheventtptheventconcat(ptheventtev,...); Thisconcatenatesoneormoreadditionaleventringstotheeventringevandreturnsev.The endoftheargumentlisthastobemarkedwithaNULLargument.Usethisfunctiontocreate realeventsringsoutofthesingle-eventringscreatedbypthevent(3). ptheventtptheventisolate(ptheventtev); Thisisolatestheeventevfrompossiblyappendedeventsintheeventring.Wheninevonly oneeventexists,thisreturnsNULL.Whenremainingeventsexists,theyformaneweventring whichisreturned. ptheventtptheventwalk(ptheventtev,intdirection); Thiswalkstothenext(whendirectionisPTH_WALK_NEXT)orpreviews(whendirectionis PTH_WALK_PREV)eventintheeventringevandreturnsthisnewreachedevent.Additionally PTH_UNTIL_OCCURREDcanbeOR-edintodirectiontowalktothenext/previousoccurred eventintheringev. pthstatustptheventstatus(ptheventtev); Thisreturnsthestatusofeventev.Thisisafastoperationbecauseonlyatagonevis checkedwhichwaseithersetorstillnotsetbythescheduler.Inotherwords:Thisdoesn’t checktheeventitself,itjustchecksthelastknowledgeofthescheduler.Thepossiblereturned statuscodesare:PTH_STATUS_PENDING(eventisstillpending),PTH_STATUS_OCCURRED(event successfullyoccurred),PTH_STATUS_FAILED(eventfailed). intptheventfree(ptheventtev,intmode); Thisdeallocatestheeventev(whenmodeisPTH_FREE_THIS)oralleventsappendedtothe eventringunderev(whenmodeisPTH_FREE_ALL). Key-BasedStorage Thefollowingfunctionsprovidethread-localstoragethroughuniquekeyssimilartothePOSIX PthreadAPI.Usethisforthreadspecificglobaldata. intpthkeycreate(pthkeyt*key,void(*func)(void*)); Thiscreatedanewuniquekeyandstoresitinkey.Additionallyfunccanspecifyadestructorfunctionwhichiscalledonthecurrentthreadsterminationwiththekey. intpthkeydelete(pthkeytkey); Thisexplicitlydestroysakeykey. intpthkeysetdata(pthkeytkey,constvoid*value); Thisstoresvalueunderkey. void*pthkeygetdata(pthkeytkey); Thisretrievesthevalueunderkey. MessagePortCommunication Thefollowingfunctionsprovidemessageportswhichcanbeusedforefficientandflexibleinterthreadcommunication. pthmsgporttpthmsgportcreate(constchar*name); Thisreturnsapointertoanewmessageport.IfnamenameisnotNULL,thenamecanbe usedbyotherthreadsviapthmsgportfind(3)tofindthemessageportincasetheydonot perlv5.8.6 2004-12-03 15 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) knowdirectlythepointertothemessageport. voidpthmsgportdestroy(pthmsgporttmp); Thisdestroysamessageportmp.Beforeallpendingmessagesonitarerepliedtotheirorigin messageport. pthmsgporttpthmsgportfind(constchar*name); Thisfindsamessageportinthesystembynameandreturnsthepointertoit. intpthmsgportpending(pthmsgporttmp); Thisreturnsthenumberofpendingmessagesonmessageportmp. intpthmsgportput(pthmsgporttmp,pthmessaget*m); Thisputs(orsends)amessagemtomessageportmp. pthmessaget*pthmsgportget(pthmsgporttmp); Thisgets(orreceives)thetopmessagefrommessageportmp.Incomingmessagesarealways keptinaqueue,sotherecanbemorependingmessages,ofcourse. intpthmsgportreply(pthmessaget*m); Thisrepliesamessagemtothemessageportofthesender. ThreadCleanups Per-threadcleanupfunctions. intpthcleanuppush(void(*handler)(void*),void*arg); Thispushestheroutinehandlerontothestackofcleanuproutinesforthecurrentthread. TheseroutinesarecalledinLIFOorderwhenthethreadterminates. intpthcleanuppop(intexecute); Thispopsthetop-mostroutinefromthestackofcleanuproutinesforthecurrentthread. WhenexecuteisTRUEtheroutineisadditionallycalled. ProcessForking Thefollowingfunctionsprovidesomespecialsupportforprocessforkingsituationsinsidethe threadingenvironment. intpthatforkpush(void(*prepare)(void*),void(*)(void*parent),void(*)(void*child),void *arg); Thisfunctiondeclaresforkinghandlerstobecalledbeforeandafterpthfork(3),inthecontextofthethreadthatcalledpthfork(3).Thepreparehandleriscalledbeforefork(2)processingcommences.Theparenthandleriscalledafterfork(2)processingcompletesinthe parentprocess.Thechildhandleriscalledafterfork(2)processingcompletedinthechild process.Ifnohandlingisdesiredatoneormoreofthesethreepoints,thecorrespondinghandlercanbegivenasNULL.Eachhandleriscalledwithargastheargument. Theorderofcallstopthatforkpush(3)issignificant.Theparentandchildhandlersare calledintheorderinwhichtheywereestablishedbycallstopthatforkpush(3),i.e.,FIFO. Theprepareforkhandlersarecalledintheoppositeorder,i.e.,LIFO. intpthatforkpop(void); Thisremovesthetop-mosthandlersontheforkinghandlerstackwhichwereestablishedwith thelastpthatforkpush(3)call.ItreturnsFALSEwhennomorehandlerscouldn’tberemoved fromthestack. pidtpthfork(void); Thisisavariantoffork(2)withthedifferencethatthecurrentthreadonlyisforkedintoa separateprocess,i.e.,intheparentprocessnothingchangeswhileinthechildprocessall threadsaregoneexceptfortheschedulerandthecallingthread.Whenyoureallywantto duplicateallthreadsinthecurrentprocessyoushouldusefork(2)directly.Butthisisusually notreasonable.Additionallythisfunctiontakescareofforkinghandlersasestablishedby perlv5.8.6 2004-12-03 16 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) pthforkpush(3). Synchronization Thefollowingfunctionsprovidesynchronizationsupportviamutualexclusionlocks(mutex), read-writelocks(rwlock),conditionvariables(cond)andbarriers(barrier).Keepinmindthat inanon-preemptivethreadingsystemlikePththismightsoundunnecessaryatthefirstlook, becauseathreadisn’tinterruptedbythesystem.Actuallywhenyouhaveacriticalcodesection whichdoesn’tcontainanypthxxx()functions,youdon’tneedanymutextoprotectit,ofcourse. Butwhenyourcriticalcodesectioncontainsanypthxxx()functionthechanceishighthatthese temporarilyswitchtothescheduler.Andthiswayotherthreadscanmakeprogressandenteryour criticalcodesection,too.Thisisespeciallytrueforcriticalcodesectionswhichimplicitlyor explicitlyusetheeventmechanism. intpthmutexinit(pthmutext*mutex); Thisdynamicallyinitializesamutexvariableoftype‘pth_mutex_t’.Alternativelyonecan alsousestaticinitializationvia‘pth_mutex_tmutex=PTH_MUTEX_INIT’. intpthmutexacquire(pthmutext*mutex,inttry,ptheventtev); Thisacquiresamutexmutex.Ifthemutexisalreadylockedbyanotherthread,thecurrent threadsexecutionissuspendeduntilthemutexisunlockedagainoradditionallytheextra eventsinevoccurred(whenevisnotNULL).Recursivelockingisexplicitlysupported,i.e.,a threadisallowedtoacquireamutexmorethanoncebeforeitsreleased.Butitthenalsohas bereleasedthesamenumberoftimesuntilthemutexisagainlockablebyothers.Whentry isTRUEthisfunctionneversuspendsexecution.InsteaditreturnsFALSEwitherrnosetto

EBUSY.

intpthmutexrelease(pthmutext*mutex); Thisdecrementstherecursionlockingcountonmutexandwhenitiszeroitreleasesthe mutexmutex. intpthrwlockinit(pthrwlockt*rwlock); Thisdynamicallyinitializesaread-writelockvariableoftype‘pth_rwlock_t’.Alternatively onecanalsousestaticinitializationvia‘pth_rwlock_trwlock=PTH_RWLOCK_INIT’. intpthrwlockacquire(pthrwlockt*rwlock,intop,inttry,ptheventtev); Thisacquiresaread-only(whenopisPTH_RWLOCK_RD)oraread-write(whenopis PTH_RWLOCK_RW)lockrwlock.Whenthelockisonlylockedbyotherthreadsinread-only mode,thelocksucceeds.Butwhenonethreadholdsaread-writelock,alllockingattempts suspendthecurrentthreaduntilthislockisreleasedagain.Additionallyineveventscanbe giventoletthelockingtimeout,etc.WhentryisTRUEthisfunctionneversuspendsexecution.InsteaditreturnsFALSEwitherrnosettoEBUSY. intpthrwlockrelease(pthrwlockt*rwlock); Thisreleasesapreviouslyacquired(read−onlyorread−write)lock. intpthcondinit(pthcondt*cond); Thisdynamicallyinitializesaconditionvariablevariableoftype‘pth_cond_t’.Alternatively onecanalsousestaticinitializationvia‘pth_cond_tcond=PTH_COND_INIT’. intpthcondawait(pthcondt*cond,pthmutext*mutex,ptheventtev); Thisawaitsaconditionsituation.ThecallerhastofollowthesemanticsofthePOSIXconditionvariables:mutexhastobeacquiredbeforethisfunctioniscalled.Theexecutionofthe currentthreadisthensuspendedeitheruntiltheeventsinevoccurred(whenevisnotNULL) orcondwasnotifiedbyanotherthreadviapthcondnotify(3).Whilethethreadiswaiting, mutexisreleased.Beforeitreturnsmutexisreacquired. intpthcondnotify(pthcondt*cond,intbroadcast); Thisnotifiedoneorallthreadswhicharewaitingoncond.WhenbroadcastisTRUEallthread arenotified,elseonlyasingle(unspecified)one. perlv5.8.6 2004-12-03 17 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) intpthbarrierinit(pthbarriert*barrier,intthreshold); Thisdynamicallyinitializesabarriervariableoftype‘pth_barrier_t’.Alternativelyonecan alsousestaticinitializationvia‘pth_barrier_tbarrier=PTH_BARRIER_INIT(threadhold)’. intpthbarrierreach(pthbarriert*barrier); Thisfunctionreachesabarrierbarrier.Ifthisisthelastthread(asspecifiedbythresholdon initofbarrier)allthreadsareawakened.Elsethecurrentthreadissuspendeduntilthelast threadreachedthebarrierandthiswayawakesallthreads.Thefunctionreturns(beside FALSEonerror)thevalueTRUEforanythreadwhichneitherreachedthebarrierasthefirst northelastthread;PTH_BARRIER_HEADLIGHTforthethreadwhichreachedthebarrierasthe firstthreadandPTH_BARRIER_TAILLIGHTforthethreadwhichreachedthebarrierasthelast thread. User-SpaceContext Thefollowingfunctionsprovideastand-alonesub-APIforuser-spacecontextswitching.Itinter-nallyisbasedonthesameunderlyingmachinecontextswitchingmechanismthethreadsinGNU Ptharebasedon.Hencethesefunctionsyoucanuseforimplementingyourownsimpleuserspacethreads.Thepth_uctx_tcontextissomewhatmodeledafterPOSIXucontext(3). Thetimerequiredtocreate(viapthuctxmake(3))auser-spacecontextcanrangefromjusta fewmicrosecondsuptoamoredramaticaltime(dependingonthemachinecontextswitching methodwhichisavailableontheplatform).Ontheotherhand,therawperformanceinswitching theuser-spacecontextsisalwaysverygood(nearlyindependentoftheusedmachinecontext switchingmethod).Forinstance,onanIntelPentium-IIICPUwith800Mhzrunningunder FreeBSD4oneusuallyachievesabout260,000user-spacecontextswitches(via pthuctxswitch(3))persecond. intpthuctxcreate(pthuctxt*uctx); Thisfunctioncreatesauser-spacecontextandstoresitintouctx.Thereisstillnounderlying user-spacecontextconfigured.Youstillhavetodothiswithpthuctxmake(3).Onsuccess, thisfunctionreturnsTRUE,elseFALSE. intpthuctxmake(pthuctxtuctx,char*skaddr,sizetsksize,constsigsett*sigmask,void (*startfunc)(void*),void*startarg,pthuctxtuctxafter); Thisfunctionmakesanewuser-spacecontextinuctxwhichwilloperateontherun-time stackskaddr(whichisofmaximumsizesksize),withthesignalsinsigmaskblocked(ifsigmaskisnotNULL)andstartingtoexecutewiththecallstartfunc(startarg).Ifskaddris NULL,astackisdynamicallyallocated.Thestacksizesksizehastobeatleast16384(16KB). IfthestartfunctionstartfuncreturnsanductxafterisnotNULL,animplicituser-spacecon-textswitchtothiscontextisperformed.Else(ifuctxafterisNULL)theprocessisterminated withexit(3).ThisfunctionissomewhatmodeledafterPOSIXmakecontext(3).Onsuccess, thisfunctionreturnsTRUE,elseFALSE. intpthuctxswitch(pthuctxtuctxfrom,pthuctxtuctxto); Thisfunctionsavesthecurrentuser-spacecontextinuctxfromforlaterrestoringbyanother calltopthuctxswitch(3)andrestoresthenewuser-spacecontextfromuctxto,whichprevi-ouslyhadtobesetwitheitherapreviouscalltopthuctxswitch(3)orinitiallyby pthuctxmake(3).ThisfunctionissomewhatmodeledafterPOSIXswapcontext(3).If uctxfromoructxtoareNULLorifuctxtocontainsnovaliduser-spacecontext,FALSEis returnedinsteadofTRUE.Thesearetheonlyerrorspossible. intpthuctxdestroy(pthuctxtuctx); Thisfunctiondestroystheuser-spacecontextinuctx.Therun-timestackassociatedwiththe user-spacecontextisdeallocatedonlyifitwasnotgivenbytheapplication(seeskaddrof pthuctxcreate(3)).IfuctxisNULL,FALSEisreturnedinsteadofTRUE.Thisistheonlyerror possible. perlv5.8.6 2004-12-03 18 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) GeneralizedPOSIXReplacementAPI ThefollowingfunctionsaregeneralizedreplacementsfunctionsforthePOSIXAPI,i.e.,theyare similartothefunctionsunder‘StandardPOSIXReplacementAPI’butallhaveanadditional eventargumentwhichcanbeusedfortimeouts,etc. intpthsigwaitev(constsigsett*set,int*sig,ptheventtev); Thisisequaltopthsigwait(3)(seebelow),buthasanadditionaleventargumentev.When pthsigwait(3)suspendsthecurrentthreadsexecutionitusuallyonlyusesthesignaleventon settoawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). intpthconnectev(ints,conststructsockaddr*addr,socklentaddrlen,ptheventtev); Thisisequaltopthconnect(3)(seebelow),buthasanadditionaleventargumentev.When pthconnect(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventons toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). intpthacceptev(ints,structsockaddr*addr,socklent*addrlen,ptheventtev); Thisisequaltopthaccept(3)(seebelow),buthasanadditionaleventargumentev.When pthaccept(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventons toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). intpthselectev(intnfd,fdset*rfds,fdset*wfds,fdset*efds,structtimeval*timeout, ptheventtev); Thisisequaltopthselect(3)(seebelow),buthasanadditionaleventargumentev.When pthselect(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventon rfds,wfdsandefdstoawake.Withthisfunctionanynumberofextraeventscanbeusedto awakethecurrentthread(rememberthatevactuallyisaneventring). intpthpollev(structpollfd*fds,unsignedintnfd,inttimeout,ptheventtev); Thisisequaltopthpoll(3)(seebelow),buthasanadditionaleventargumentev.When pthpoll(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfds toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthreadev(intfd,void*buf,sizetnbytes,ptheventtev); Thisisequaltopthread(3)(seebelow),buthasanadditionaleventargumentev.When pthread(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfd toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthreadvev(intfd,conststructiovec*iovec,intiovcnt,ptheventtev); Thisisequaltopthreadv(3)(seebelow),buthasanadditionaleventargumentev.When pthreadv(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfd toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthwriteev(intfd,constvoid*buf,sizetnbytes,ptheventtev); Thisisequaltopthwrite(3)(seebelow),buthasanadditionaleventargumentev.When pthwrite(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfd toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthwritevev(intfd,conststructiovec*iovec,intiovcnt,ptheventtev); Thisisequaltopthwritev(3)(seebelow),buthasanadditionaleventargumentev.When pthwritev(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfd toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). perlv5.8.6 2004-12-03 19 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) ssizetpthrecvev(intfd,void*buf,sizetnbytes,intflags,ptheventtev); Thisisequaltopthrecv(3)(seebelow),buthasanadditionaleventargumentev.When pthrecv(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfdto awake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthrecvfromev(intfd,void*buf,sizetnbytes,intflags,structsockaddr*from, socklent*fromlen,ptheventtev); Thisisequaltopthrecvfrom(3)(seebelow),buthasanadditionaleventargumentev.When pthrecvfrom(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventon fdtoawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthsendev(intfd,constvoid*buf,sizetnbytes,intflags,ptheventtev); Thisisequaltopthsend(3)(seebelow),buthasanadditionaleventargumentev.When pthsend(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfd toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). ssizetpthsendtoev(intfd,constvoid*buf,sizetnbytes,intflags,conststructsockaddr*to, socklenttolen,ptheventtev); Thisisequaltopthsendto(3)(seebelow),buthasanadditionaleventargumentev.When pthsendto(3)suspendsthecurrentthreadsexecutionitusuallyonlyusestheI/Oeventonfd toawake.Withthisfunctionanynumberofextraeventscanbeusedtoawakethecurrent thread(rememberthatevactuallyisaneventring). StandardPOSIXReplacementAPI ThefollowingfunctionsarestandardreplacementsfunctionsforthePOSIXAPI.Thedifferenceis mainlythattheysuspendthecurrentthreadonlyinsteadofthewholeprocessincasethefile descriptorswillblock. intpthnanosleep(conststructtimespec*rqtp,structtimespec*rmtp); ThisisavariantofthePOSIXnanosleep(3)function.Itsuspendsthecurrentthreadsexecutionuntiltheamountoftimeinrqtpelapsed.Thethreadisguaranteedtonotwakeup beforethistime,butbecauseofthenon-preemptiveschedulingnatureofPth,itcanbe awakenedlater,ofcourse.IfrmtpisnotNULL,thetimespecstructureitreferencesisupdated tocontaintheunsleptamount(therequesttimeminusthetimeactuallyslepttime).Thedifferencebetweennanosleep(3)andpthnanosleep(3)isthatthatpthnanosleep(3)suspends onlytheexecutionofthecurrentthreadandnotthewholeprocess. intpthusleep(unsignedintusec); Thisisavariantofthe4.3BSDusleep(3)function.Itsuspendsthecurrentthreadsexecution untilusecmicroseconds(=usec*1/1000000sec)elapsed.Thethreadisguaranteedtonot wakeupbeforethistime,butbecauseofthenon-preemptiveschedulingnatureofPth,itcan beawakenedlater,ofcourse.Thedifferencebetweenusleep(3)andpthusleep(3)isthatthat pthusleep(3)suspendsonlytheexecutionofthecurrentthreadandnotthewholeprocess. unsignedintpthsleep(unsignedintsec); ThisisavariantofthePOSIXsleep(3)function.Itsuspendsthecurrentthreadsexecution untilsecsecondselapsed.Thethreadisguaranteedtonotwakeupbeforethistime,but becauseofthenon-preemptiveschedulingnatureofPth,itcanbeawakenedlater,ofcourse. Thedifferencebetweensleep(3)andpthsleep(3)isthatpthsleep(3)suspendsonlytheexecutionofthecurrentthreadandnotthewholeprocess. pidtpthwaitpid(pidtpid,int*status,intoptions); ThisisavariantofthePOSIXwaitpid(2)function.Itsuspendsthecurrentthreadsexecution untilstatusinformationisavailableforaterminatedchildprocesspid.Thedifference betweenwaitpid(2)andpthwaitpid(3)isthatpthwaitpid(3)suspendsonlytheexecutionof perlv5.8.6 2004-12-03 20 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) thecurrentthreadandnotthewholeprocess.Formoredetailsabouttheargumentsand returncodesemanticsseewaitpid(2). intpthsystem(constchar*cmd); ThisisavariantofthePOSIXsystem(3)function.Itexecutestheshellcommandcmdwith BourneShell(sh)andsuspendsthecurrentthreadsexecutionuntilthiscommandterminates. Thedifferencebetweensystem(3)andpthsystem(3)isthatpthsystem(3)suspendsonlythe executionofthecurrentthreadandnotthewholeprocess.Formoredetailsabouttheargumentsandreturncodesemanticsseesystem(3). intpthsigmask(inthow,constsigsett*set,sigsett*oset) ThisisthePththread-relatedequivalentofPOSIXsigprocmask(2)respectivelypthreadsig-mask(3).Theargumentshow,setandosetdirectlyrelatetosigprocmask(2),becausePth internallyjustusessigprocmask(2)here.Soalternativelyyoucanalsodirectlycallsigprocmask(2),butforconsistencyreasonsyoushouldusethisfunctionpthsigmask(3). intpthsigwait(constsigsett*set,int*sig); ThisisavariantofthePOSIX.1csigwait(3)function.Itsuspendsthecurrentthreadsexecutionuntilasignalinsetoccurredandstoresthesignalnumberinsig.Theimportantpointis thatthesignalisnotdeliveredtoasignalhandler.Insteadit’scaughtbythescheduleronly inordertoawakethepthsigwait()call.Thetrickandnoticeablepointhereisthatthisway yougetanasynchronousawareapplicationthatiswrittencompletelysynchronously.When youthinkabouttheproblemofasynchronoussafefunctionsyoushouldrecognizethatthisis agreatbenefit. intpthconnect(ints,conststructsockaddr*addr,socklentaddrlen); Thisisavariantofthe4.2BSDconnect(2)function.Itestablishesaconnectiononasockets totargetspecifiedinaddrandaddrlen.Thedifferencebetweenconnect(2)andpthconnect(3)isthatpthconnect(3)suspendsonlytheexecutionofthecurrentthreadandnotthe wholeprocess.Formoredetailsabouttheargumentsandreturncodesemanticsseeconnect(2). intpthaccept(ints,structsockaddr*addr,socklent*addrlen); Thisisavariantofthe4.2BSDaccept(2)function.Itacceptsaconnectiononasocketby extractingthefirstconnectionrequestonthequeueofpendingconnections,creatinganew socketwiththesamepropertiesofsandallocatesanewfiledescriptorforthesocket(which isreturned).Thedifferencebetweenaccept(2)andpthaccept(3)isthatpthaccept(3)suspendsonlytheexecutionofthecurrentthreadandnotthewholeprocess.Formoredetails abouttheargumentsandreturncodesemanticsseeaccept(2). intpthselect(intnfd,fdset*rfds,fdset*wfds,fdset*efds,structtimeval*timeout); Thisisavariantofthe4.2BSDselect(2)function.ItexaminestheI/Odescriptorsetswhose addressesarepassedinrfds,wfds,andefdstoseeifsomeoftheirdescriptorsarereadyfor reading,arereadyforwriting,orhaveanexceptionalconditionpending,respectively.For moredetailsabouttheargumentsandreturncodesemanticsseeselect(2). intpthpselect(intnfd,fdset*rfds,fdset*wfds,fdset*efds,conststructtimespec*timeout, constsigsett*sigmask); ThisisavariantofthePOSIXpselect(2)function,whichinturnisastrongervariantof 4.2BSDselect(2).Thedifferenceisthatthehigher-resolutionstructtimespecispassed insteadofthelower-resolutionstructtimevalandthatasignalmaskisspecifiedwhichis temporarilysetwhilewaitingforinput.Formoredetailsabouttheargumentsandreturn codesemanticsseepselect(2)andselect(2). intpthpoll(structpollfd*fds,unsignedintnfd,inttimeout); ThisisavariantoftheSysVpoll(2)function.ItexaminestheI/Odescriptorswhichare passedinthearrayfdstoseeifsomeofthemarereadyforreading,arereadyforwriting,or haveanexceptionalconditionpending,respectively.Formoredetailsaboutthearguments andreturncodesemanticsseepoll(2). perlv5.8.6 2004-12-03 21 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) ssizetpthread(intfd,void*buf,sizetnbytes); ThisisavariantofthePOSIXread(2)function.Itreadsuptonbytesbytesintobuffromfile descriptorfd.Thedifferencebetweenread(2)andpthread(2)isthatpthread(2)suspends executionofthecurrentthreaduntilthefiledescriptorisreadyforreading.Formoredetails abouttheargumentsandreturncodesemanticsseeread(2). ssizetpthreadv(intfd,conststructiovec*iovec,intiovcnt); ThisisavariantofthePOSIXreadv(2)function.Itreadsdatafromfiledescriptorfdintothe firstiovcntrowsoftheiovvector.Thedifferencebetweenreadv(2)andpthreadv(2)isthat pthreadv(2)suspendsexecutionofthecurrentthreaduntilthefiledescriptorisreadyfor reading.Formoredetailsabouttheargumentsandreturncodesemanticsseereadv(2). ssizetpthwrite(intfd,constvoid*buf,sizetnbytes); ThisisavariantofthePOSIXwrite(2)function.Itwritesnbytesbytesfrombuftofile descriptorfd.Thedifferencebetweenwrite(2)andpthwrite(2)isthatpthwrite(2)suspendsexecutionofthecurrentthreaduntilthefiledescriptorisreadyforwriting.Formore detailsabouttheargumentsandreturncodesemanticsseewrite(2). ssizetpthwritev(intfd,conststructiovec*iovec,intiovcnt); ThisisavariantofthePOSIXwritev(2)function.Itwritesdatatofiledescriptorfdfromthe firstiovcntrowsoftheiovvector.Thedifferencebetweenwritev(2)andpthwritev(2)isthat pthwritev(2)suspendsexecutionofthecurrentthreaduntilthefiledescriptorisreadyfor reading.Formoredetailsabouttheargumentsandreturncodesemanticsseewritev(2). ssizetpthpread(intfd,void*buf,sizetnbytes,offtoffset); ThisisavariantofthePOSIXpread(3)function.Itperformsthesameactionasaregular read(2),exceptthatitreadsfromagivenpositioninthefilewithoutchangingthefile pointer.Thefirstthreeargumentsarethesameasforpthread(3)withtheadditionofa fourthargumentoffsetforthedesiredpositioninsidethefile. ssizetpthpwrite(intfd,constvoid*buf,sizetnbytes,offtoffset); ThisisavariantofthePOSIXpwrite(3)function.Itperformsthesameactionasaregular write(2),exceptthatitwritestoagivenpositioninthefilewithoutchangingthefilepointer. Thefirstthreeargumentsarethesameasforpthwrite(3)withtheadditionofafourthargumentoffsetforthedesiredpositioninsidethefile. ssizetpthrecv(intfd,void*buf,sizetnbytes,intflags); ThisisavariantoftheSUSv2recv(2)functionandequalto‘‘pthrecvfrom(fd,buf,nbytes, flags,NULL,0)’’. ssizetpthrecvfrom(intfd,void*buf,sizetnbytes,intflags,structsockaddr*from,socklent *fromlen); ThisisavariantoftheSUSv2recvfrom(2)function.Itreadsuptonbytesbytesintobuffrom filedescriptorfdwhileusingflagsandfrom/fromlen.Thedifferencebetweenrecvfrom(2)and pthrecvfrom(2)isthatpthrecvfrom(2)suspendsexecutionofthecurrentthreaduntilthe filedescriptorisreadyforreading.Formoredetailsabouttheargumentsandreturncode semanticsseerecvfrom(2). ssizetpthsend(intfd,constvoid*buf,sizetnbytes,intflags); ThisisavariantoftheSUSv2send(2)functionandequalto‘‘pthsendto(fd,buf,nbytes, flags,NULL,0)’’. ssizetpthsendto(intfd,constvoid*buf,sizetnbytes,intflags,conststructsockaddr*to, socklenttolen); ThisisavariantoftheSUSv2sendto(2)function.Itwritesnbytesbytesfrombuftofile descriptorfdwhileusingflagsandto/tolen.Thedifferencebetweensendto(2)and pthsendto(2)isthatpthsendto(2)suspendsexecutionofthecurrentthreaduntilthefile descriptorisreadyforwriting.Formoredetailsabouttheargumentsandreturncodesemanticsseesendto(2). perlv5.8.6 2004-12-03 22 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) EXAMPLE ThefollowingexampleisauselessserverwhichdoesnothingmorethanlisteningonTCPport 12345anddisplayingthecurrenttimetothesocketwhenaconnectionwasestablished.Foreach incomingconnectionathreadisspawned.Additionally,toseemoremultithreading,auseless tickerthreadrunssimultaneouslywhichoutputsthecurrenttimetostderrevery5seconds.The examplecontainsnoerrorcheckingandisonlyintendedtoshowyouthelookandfeelofPth.

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<signal.h>
#include<netdb.h>
#include<unistd.h>
#include"pth.h"
#definePORT12345
/*thesocketconnectionhandlerthread*/
staticvoid*handler(void*_arg)
{
intfd=(int)_arg;
time_tnow;
char*ct;
now=time(NULL);
ct=ctime(&now);
pth_write(fd,ct,strlen(ct));
close(fd);
returnNULL;
}
/*thestderrtimetickerthread*/
staticvoid*ticker(void*_arg)
{
time_tnow;
char*ct;
floatload;
for(;;){
pth_sleep(5);
now=time(NULL);
ct=ctime(&now);
ct[strlen(ct)-1]='\0';
pth_ctrl(PTH_CTRL_GETAVLOAD,&load);
printf("ticker:time:%s,averageload:%.2f\n",ct,load);
}
}

perlv5.8.6 2004-12-03 23 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

/*themainthread/procedure*/
intmain(intargc,char*argv[])
{
pth_attr_tattr;
structsockaddr_insar;
structprotoent*pe;
structsockaddr_inpeer_addr;
intpeer_len;
intsa,sw;
intport;
pth_init();
signal(SIGPIPE,SIG_IGN);
attr=pth_attr_new();
pth_attr_set(attr,PTH_ATTR_NAME,"ticker");
pth_attr_set(attr,PTH_ATTR_STACK_SIZE,64*1024);
pth_attr_set(attr,PTH_ATTR_JOINABLE,FALSE);
pth_spawn(attr,ticker,NULL);
pe=getprotobyname("tcp");
sa=socket(AF_INET,SOCK_STREAM,pe->p_proto);
sar.sin_family=AF_INET;
sar.sin_addr.s_addr=INADDR_ANY;
sar.sin_port=htons(PORT);
bind(sa,(structsockaddr*)&sar,sizeof(structsockaddr_in));
listen(sa,10);
pth_attr_set(attr,PTH_ATTR_NAME,"handler");
for(;;){
peer_len=sizeof(peer_addr);
sw=pth_accept(sa,(structsockaddr*)&peer_addr,&peer_len);
pth_spawn(attr,handler,(void*)sw);
}
}

BUILDENVIRONMENTS InthissectionwewilldiscussthecanonicalwaystoestablishthebuildenvironmentforaPth basedprogram.ThepossibilitiessupportedbyPthrangefromverysimpleenvironmentstorather complexones. ManualBuildEnvironment(Novice) Asafirstexample,assumewehavetheabovetestprogramstayinginthesourcefilefoo.c.Then wecancreateaverysimplebuildenvironmentbyjustaddingthefollowingMakefile: perlv5.8.6 2004-12-03 24 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

$viMakefile
|CC=cc
|CFLAGS=`pth-config--cflags`
|LDFLAGS=`pth-config--ldflags`
|LIBS=`pth-config--libs`

|

|all:foo
|foo:foo.o
|$(CC)$(LDFLAGS)-ofoofoo.o$(LIBS)
|foo.o:foo.c
|$(CC)$(CFLAGS)-cfoo.c
|clean:
|rm-ffoofoo.o

Thisimportsthenecessarycompilerandlinkerflagson-the-flyfromthePthinstallationviaits pth-configprogram.Thisapproachisstraight-forwardandworksfineforsmallprojects. AutoconfBuildEnvironment(Advanced) Thepreviousapproachissimplebutinflexible.First,tospeedupbuilding,itwouldbenicetonot expandthecompilerandlinkerflagseverytimethecompilerisstarted.Second,itwouldbeuseful toalsobeabletobuildagainstuninstalledPth,thatis,againstaPthsourcetreewhichwasjust configuredandbuilt,butnotinstalled.Third,itwouldbealsousefultoallowcheckingofthePth versiontomakesureitisatleastaminimumrequiredversion.Andfinally,itwouldbealsogreat tomakesurePthworkscorrectlybyfirstperformingsomesanitycompileandrun-timechecks. AllthiscanbedoneifweuseGNUautoconfandtheAC_CHECK_PTHmacroprovidedbyPth.For this,weestablishthefollowingthreefiles: FirstweagainneedtheMakefile,butthistimeitcontainsautoconfplaceholdersandadditional cleanuptargets.AndwecreateitunderthenameMakefile.in,becauseitisnowaninputfilefor autoconf:

$viMakefile.in
|CC=@CC@
|CFLAGS=@CFLAGS@
|LDFLAGS=@LDFLAGS@
|LIBS=@LIBS@

|

|all:foo
|foo:foo.o
|$(CC)$(LDFLAGS)-ofoofoo.o$(LIBS)
|foo.o:foo.c
|$(CC)$(CFLAGS)-cfoo.c
|clean:
|rm-ffoofoo.o
|distclean:
|rm-ffoofoo.o
|rm-fconfig.logconfig.statusconfig.cache
|rm-fMakefile

Becauseautoconfgeneratesadditionalfiles,weaddedacanonicaldistcleantargetwhichcleans thisup.Secondly,wewroteconfigure.ac,a(minimal)autoconfscriptspecification:

$viconfigure.ac
|AC_INIT(Makefile.in)
|AC_CHECK_PTH(1.3.0)
|AC_OUTPUT(Makefile)

Thenweletautoconf’saclocalprogramgenerateforusanaclocal.m4filecontainingPth’s perlv5.8.6 2004-12-03 25 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) AC_CHECK_PTHmacro.Thenwegeneratethefinalconfigurescriptoutofthisaclocal.m4file

andtheconfigure.acfile:
$aclocal--acdir=`pth-config--acdir`
$autoconf

Afterthesesteps,theworkingdirectoryshouldlooksimilartothis:

$ls-l
-rw-r--r--1rseusers176Nov311:11Makefile.in
-rw-r--r--1rseusers15314Nov311:16aclocal.m4
-rwxr-xr-x1rseusers52045Nov311:16configure
-rw-r--r--1rseusers63Nov311:11configure.ac
-rw-r--r--1rseusers4227Nov311:11foo.c

IfwenowrunconfigurewegetacorrectMakefilewhichimmediatelycanbeusedtobuildfoo (assumingthatPthisalreadyinstalledsomewhere,sothatpth-configisin$PATH):

$./configure
creatingcache./config.cache
checkingforgcc...gcc
checkingwhethertheCcompiler(gcc)works...yes
checkingwhethertheCcompiler(gcc)isacross-compiler...no
checkingwhetherweareusingGNUC...yes
checkingwhethergccaccepts-g...yes
checkinghowtoruntheCpreprocessor...gcc-E
checkingforGNUPth...version1.3.0,installedunder/usr/local
updatingcache./config.cache
creating./config.status
creatingMakefile
rse@en1:/e/gnu/pth/ac
$make
gcc-g-O2-I/usr/local/include-cfoo.c
gcc-L/usr/local/lib-ofoofoo.o-lpth

IfPthisinstalledinnon-standardlocationsorpth-configisnotin$PATH,onejusthastodrop theconfigurescriptanoteaboutthelocationbyrunningconfigurewiththeoption --with-pth=dir(wherediristheargumentwhichwasusedwiththe--prefixoptionwhenPth wasinstalled). AutoconfBuildEnvironmentwithLocalCopyofPth(Expert) FinallyletusassumethefooprogramstaysundereitheraGPLorLGPLdistributionlicenseand wewanttomakeitastand-alonepackageforeasierdistributionandinstallation.Thatis,we don’twanttoobligetheend-usertoinstallPthjusttoallowourfoopackagetocompile.For this,itisaconvenientpracticetoincludetherequiredlibraries(herePth)intothesourcetreeof thepackage(herefoo).Pthshipswithallnecessarysupporttoallowustoeasilyachievethis approach.Say,wewantPthinasubdirectorynamedpth/andthisdirectoryshouldbeseamlesslyintegratedintotheconfigurationandbuildprocessoffoo. FirstweagainstartwiththeMakefile.in,butthistimeitisamoreadvancedversionwhichsupportssubdirectorymovement: perlv5.8.6 2004-12-03 26 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

$viMakefile.in
|CC=@CC@
|CFLAGS=@CFLAGS@
|LDFLAGS=@LDFLAGS@
|LIBS=@LIBS@

|

|SUBDIRS=pth

|

|all:subdirs_allfoo

|

|subdirs_all:
|@$(MAKE)$(MFLAGS)subdirsTARGET=all
|subdirs_clean:
|@$(MAKE)$(MFLAGS)subdirsTARGET=clean
|subdirs_distclean:
|@$(MAKE)$(MFLAGS)subdirsTARGET=distclean
|subdirs:
|@forsubdirin$(SUBDIRS);do\
|echo"===>$$subdir($(TARGET))";\
|(cd$$subdir;$(MAKE)$(MFLAGS)$(TARGET)||exit1)||exit1;\
|echo"<===$$subdir";\
|done

|

|foo:foo.o
|$(CC)$(LDFLAGS)-ofoofoo.o$(LIBS)
|foo.o:foo.c
|$(CC)$(CFLAGS)-cfoo.c

|

|clean:subdirs_clean
|rm-ffoofoo.o
|distclean:subdirs_distclean
|rm-ffoofoo.o
|rm-fconfig.logconfig.statusconfig.cache
|rm-fMakefile

Thenwecreateaslightlydifferentautoconfscriptconfigure.ac:

$viconfigure.ac
|AC_INIT(Makefile.in)
|AC_CONFIG_AUX_DIR(pth)
|AC_CHECK_PTH(1.3.0,subdir:pth--disable-tests)
|AC_CONFIG_SUBDIRS(pth)
|AC_OUTPUT(Makefile)

Hereweprovidedadefaultvalueforfoo’s--with-pthoptionasthesecondargumentto AC_CHECK_PTHwhichindicatesthatPthcanbefoundinthesubdirectorynamedpth/.Additionallywespecifiedthatthe--disable-testsoptionofPthshouldbepassedtothepth/subdirec-tory,becauseweneedonlytobuildthePthlibraryitself.AndweaddedaAC_CONFIG_SUBDIR callwhichindicatestoautoconfthatitshouldconfigurethepth/subdirectory,too.The AC_CONFIG_AUX_DIRdirectivewasaddedjusttomakeautoconfhappy,becauseitwantstofinda

install.shorshtoolscriptifAC_CONFIG_SUBDIRSisused.

Nowweletautoconf’saclocalprogramagaingenerateforusanaclocal.m4filewiththecontentsofPth’sAC_CHECK_PTHmacro.Finallywegeneratetheconfigurescriptoutofthis

aclocal.m4fileandtheconfigure.acfile.

perlv5.8.6 2004-12-03 27 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

$aclocal--acdir=`pth-config--acdir`
$autoconf

Nowwehavetocreatethepth/subdirectoryitself.Forthis,weextractthePthdistributionto thefoosourcetreeandjustrenameittopth/:

$gunzip<pth-X.Y.Z.tar.gz|tarxvf-
$mvpth-X.Y.Zpth

Optionallytoreducethesizeofthepth/subdirectory,wecanstripdownthePthsourcestoa minimumwiththestripteasefeature:

$cdpth
$./configure
$makestriptease
$cd..

Afterthisthesourcetreeoffooshouldlooksimilartothis:

$ls-l
-rw-r--r--1rseusers709Nov311:51Makefile.in
-rw-r--r--1rseusers16431Nov312:20aclocal.m4
-rwxr-xr-x1rseusers57403Nov312:21configure
-rw-r--r--1rseusers129Nov312:21configure.ac
-rw-r--r--1rseusers4227Nov311:11foo.c
drwxr-xr-x2rseusers3584Nov312:36pth
$ls-lpth/
-rw-rw-r--1rseusers26344Nov120:12COPYING
-rw-rw-r--1rseusers2042Nov312:36Makefile.in
-rw-rw-r--1rseusers3967Nov119:48README
-rw-rw-r--1rseusers340Nov312:36README.1st
-rw-rw-r--1rseusers28719Oct3117:06config.guess
-rw-rw-r--1rseusers24274Aug1813:31config.sub
-rwxrwxr-x1rseusers155141Nov312:36configure
-rw-rw-r--1rseusers162021Nov312:36pth.c
-rw-rw-r--1rseusers18687Nov215:19pth.h.in
-rw-rw-r--1rseusers5251Oct3112:46pth_acdef.h.in
-rw-rw-r--1rseusers2120Nov111:27pth_acmac.h.in
-rw-rw-r--1rseusers2323Nov111:27pth_p.h.in
-rw-rw-r--1rseusers946Nov111:27pth_vers.c
-rw-rw-r--1rseusers26848Nov111:27pthread.c
-rw-rw-r--1rseusers18772Nov111:27pthread.h.in
-rwxrwxr-x1rseusers26188Nov312:36shtool

Nowwhenweconfigureandbuildthefoopackageitlookssimilartothis: perlv5.8.6 2004-12-03 28 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1)

$./configure
creatingcache./config.cache
checkingforgcc...gcc
checkingwhethertheCcompiler(gcc)works...yes
checkingwhethertheCcompiler(gcc)isacross-compiler...no
checkingwhetherweareusingGNUC...yes
checkingwhethergccaccepts-g...yes
checkinghowtoruntheCpreprocessor...gcc-E
checkingforGNUPth...version1.3.0,localunderpth
updatingcache./config.cache
creating./config.status
creatingMakefile
configuringinpth
running/bin/sh./configure--enable-subdir--enable-batch
--disable-tests--cache-file=.././config.cache--srcdir=.
loadingcache.././config.cache
checkingforgcc...(cached)gcc
checkingwhethertheCcompiler(gcc)works...yes
checkingwhethertheCcompiler(gcc)isacross-compiler...no
[...]
$make
===>pth(all)
./shtoolscpp-opth_p.h-tpth_p.h.in-Dcpp-Cintern-M'==#=='pth.c
pth_vers.c
gcc-c-I.-O2-pipepth.c
gcc-c-I.-O2-pipepth_vers.c
arrclibpth.apth.opth_vers.o
ranliblibpth.a
<===pth
gcc-g-O2-Ipth-cfoo.c
gcc-Lpth-ofoofoo.o-lpth

Asyoucansee,autoconfnowautomaticallyconfiguresthelocal(strippeddown)copyofPthin thesubdirectorypth/andtheMakefileautomaticallybuildsthesubdirectory,too. SYSTEMCALLWRAPPERFACILITY PthperdefaultusesanexplicitAPI,includingthesystemcalls.Forinstanceyou’vetoexplicitly usepthread(3)whenyouneedathread-awareread(3)andcannotexpectthatbyjustcalling read(3)onlythecurrentthreadisblocked.Insteadwiththestandardread(3)callthewhole processwillbeblocked.Butbecauseforsomeapplications(mainlythoseconsistingoflotsof third-partystuff)thiscanbeinconvenient.Hereit’srequiredthatacalltoread(3)‘magically’ meanspthread(3).TheproblemhereisthatsuchmagicPthcannotprovideperdefaultbecause it’snotreallyportable.NeverthelessPthprovidesatwostepapproachtosolvethisproblem: SoftSystemCallMapping ThisvariantisavailableonallplatformsandcanalwaysbeenabledbybuildingPthwith --enable-syscall-soft.Thisthentriggerssome#define’sinthepth.hheaderwhichmapfor instanceread(3)topthread(3),etc.Currentlythefollowingfunctionsaremapped:fork(2), nanosleep(3),usleep(3),sleep(3),sigwait(3),waitpid(2),system(3),select(2),poll(2),connect(2), accept(2),read(2),write(2),recv(2),send(2),recvfrom(2),sendto(2). Thedrawbackofthisapproachisjustthatreallyallsourcefilesoftheapplicationwherethese functioncallsoccurhavetoincludepth.h,ofcourse.Andthisalsomeansthatexistinglibraries, includingthevendor’sstdio,usuallywillstillblockthewholeprocessifoneofitsI/Ofunctions block. perlv5.8.6 2004-12-03 29 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) HardSystemCallMapping Thisvariantisavailableonlyonthoseplatformswherethesyscall(2)functionexistsandthereit canbeenabledbybuildingPthwith--enable-syscall-hard.Thisthenbuildswrapperfunc-tions(forinstancesread(3))intothePthlibrarywhichinternallycalltherealPthreplacement functions(pthread(3)).Currentlythefollowingfunctionsaremapped:fork(2),nanosleep(3), usleep(3),sleep(3),waitpid(2),system(3),select(2),poll(2),connect(2),accept(2),read(2), write(2). Thedrawbackofthisapproachisthatitdependsonsyscall(2)interfaceandprototypeconflicts canoccurwhilebuildingthewrapperfunctionsduetodifferentfunctionsignaturesinthevendor Cheaderfiles.Buttheadvantageofthismappingvariantisthatthesourcefilesoftheapplicationwherethesefunctioncallsoccurhavenottoincludepth.handthatexistinglibraries,includingthevendor’sstdio,magicallybecomethread-aware(andthenblockonlythecurrentthread). IMPLEMENTATIONNOTES Pthisveryportablebecauseithasonlyonepartwhichperhapshastobeportedtonewplatforms(themachinecontextinitialization).Butitiswritteninawaywhichworksonmostlyall Unixplatformswhichsupportmakecontext(2)oratleastsigstack(2)orsigaltstack(2)[see pth_mctx.cfordetails].AnyotherPthcodeisPOSIXandANSICbasedonly. ThecontextswitchingisdoneviaeitherSUSv2makecontext(2)orPOSIXmake[sig]setjmp(3)and [sig]longjmp(3).HereallCPUregisters,theprogramcounterandthestackpointerareswitched. AdditionallythePthdispatcherswitchesalsotheglobalUnixerrnovariable[seepth_mctx.cfor details]andthesignalmask(eitherimplicitlyviasigsetjmp(3)orinanemulatedwayviaexplicit setprocmask(2)calls). ThePtheventmanagerismainlyselect(2)andgettimeofday(2)based,i.e.,thecurrenttimeis fetchedviagettimeofday(2)oncepercontextswitchfortimecalculationsandallI/Oeventsare implementedviaasinglecentralselect(2)call[seepth_sched.cfordetails]. Thethreadcontrolblockmanagementisdoneviavirtualpriorityqueueswithoutanyadditional datastructureoverhead.Forthis,thequeuelinkageattributesarepartofthethreadcontrol blocksandthequeuesareactuallyimplementedasringswithaselectedelementastheentry point[seepth_tcb.handpth_pqueue.cfordetails]. Mosttimecriticalcodesections(especiallythedispatcherandeventmanager)arespeededupby inlinefunctions(implementedasANSICpre-processormacros).Additionallyanydebuggingcode iscompletelyremovedfromthesourcewhennotbuiltwith-DPTH_DEBUG(seeAutoconf --enable-debugoption),i.e.,notonlystubfunctionsremain[seepth_debug.cfordetails]. RESTRICTIONS Pth(intentionally)providesnoreplacementsfornon-thread-safefunctions(likestrtok(3)which usesastaticinternalbuffer)orsynchronoussystemfunctions(likegethostbyname(3)which doesn’tprovideanasynchronousmodewhereitdoesn’tblock).Whenyouwanttousethosefunctionsinyourserverapplicationtogetherwiththreads,you’vetoeitherlinktheapplicationagainst specialthird-partylibraries(orforthread−safe/reentrantfunctionspossiblyagainstanexisting libc_roftheplatformvendor).ForanasynchronousDNSresolverlibraryusetheGNUadns packagefromIanJackson(seehttp://www.gnu.org/software/adns/adns.html). HISTORY ThePthlibrarywasdesignedandimplementedbetweenFebruaryandJuly1999byRalfS. Engelschallafterevaluatingnumerous(mostlypreemptive)threadlibrariesandafterintensivediscussionswithPeterSimons,MartinKraemer,LarsEilebrechtandRalphBabelrelatedtoan experimental(matrixbased)non-preemptiveC++schedulerclasswrittenbyPeterSimons. Pthwasthenimplementedinordertocombinethenon-preemptiveapproachofmultithreading (whichprovidesbetterportabilityandperformance)withanAPIsimilartothepopularonefound inPthreadlibraries(whichprovideseasyprogramming). Sotheessentialideaofthenon-preemptiveapproachwastakenoverfromPeterSimonsscheduler. perlv5.8.6 2004-12-03 30 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) TheprioritybasedschedulingalgorithmwassuggestedbyMartinKraemer.Somecodeinspiration alsocamefromanexperimentalthreadinglibrary(rsthreads)writtenbyRobertS.Thauforan ancientinternaltestversionoftheApachewebserver.TheconceptandAPIofmessageportswas borrowedfromAmigaOS’Execsubsystem.Theconceptandideafortheflexibleeventmechanism camefromPaulVixie’seventlib(whichcanbefoundasapartofBINDv8). BUGREPORTSANDSUPPORT IfyouthinkyouhavefoundabuginPth,youshouldsendareportascompleteaspossibleto bug-pth@gnu.org.Ifyoucan,pleasetrytofixtheproblemandincludeapatch,madewith’diff -u3’,inyourreport.Always,atleast,includeareasonableamountofdescriptioninyourreportto allowtheauthortodeterministicallyreproducethebug. Forfurthersupportyouadditionallycansubscribetothepth-users@gnu.orgmailinglistbysend-inganEmailtopth-users-request@gnu.orgwith‘subscribepth-users’(or‘subscribe pth-usersaddress’ifyouwanttosubscribefromaparticularEmailaddress)inthebody.Then youcandiscussyourissueswithotherPthusersbysendingmessagestopth-users@gnu.org.Cur-rently(asofAugust2000)youcanreachabout110Pthusersonthismailinglist.Oldpostings youcanfindathttp://www.mail-archive.com/pth-users@gnu.org/. SEEALSO RelatedWebLocations ‘comp.programming.threadsNewsgroupArchive’,http://www.deja.com/topicsif.xp? search=topic&group=comp.programming.threads ‘comp.programming.threadsFrequentlyAskedQuestions(F.A.Q.)’,http://www.lambdacs.com/newsgroup/FAQ.html ‘Multithreading-DefinitionsandGuidelines’,NumericQuestInc1998; http://www.numeric−quest.com/lang/multi−frame.html ‘TheSingleUNIXSpecification,Version2-Threads’,TheOpenGroup1997;http://www.open-group.org/onlinepubs/007908799/xsh/threads.html SMIThreadResources,SunMicrosystemsInc;http://www.sun.com/workshop/threads/ Bibliographyonthreadsandmultithreading,TorstenAmundsen;http://liinwww.ira.uka.de/bibliography/Os/threads.html RelatedBooks B.Nichols,D.Buttlar,J.P.Farrel:‘PthreadsProgramming-APOSIXStandardforBetterMulti-processing’,O’Reilly1996;ISBN1−56592−115−1 B.Lewis,D.J.Berg:‘MultithreadedProgrammingwithPthreads’,SunMicrosystemsPress,PrenticeHall1998;ISBN0−13−680729−1 B.Lewis,D.J.Berg:‘ThreadsPrimer-AGuideToMultithreadedProgramming’,PrenticeHall 1996;ISBN0−13−443698−9 S.J.Norton,M.D.Dipasquale:‘ThreadTime-TheMultithreadedProgrammingGuide’,Prentice Hall1997;ISBN0−13−190067−6 D.R.Butenhof:‘ProgrammingwithPOSIXThreads’,AddisonWesley1997;ISBN0−201−63392−2 RelatedManpages pth-config(1),pthread(3). getcontext(2),setcontext(2),makecontext(2),swapcontext(2),sigstack(2),sigaltstack(2),sigaction(2),sigemptyset(2),sigaddset(2),sigprocmask(2),sigsuspend(2),sigsetjmp(3),siglongjmp(3), setjmp(3),longjmp(3),select(2),gettimeofday(2). perlv5.8.6 2004-12-03 31 PTH-MANUAL(1)UserContributedPerlDocumentationPTH-MANUAL(1) AUTHOR

RalfS.Engelschall
rse@engelschall.com
www.engelschall.com

perlv5.8.6 2004-12-03 32