Multithreaded Programming Guide SunMicrosystems,Inc. 4150NetworkCircle SantaClara,CA95054 U.S.A. PartNo:816–5137–12 September2008 Copyright2008SunMicrosystems,Inc. 4150NetworkCircle,SantaClara,CA95054U.S.A. Allrightsreserved. SunMicrosystems,Inc.hasintellectualpropertyrightsrelatingtotechnologyembodiedintheproductthatisdescribedinthisdocument.Inparticular,andwithout limitation,theseintellectualpropertyrightsmayincludeoneormoreU.S.patentsorpendingpatentapplicationsintheU.S.andinothercountries. U.S.GovernmentRights–Commercialsoftware.GovernmentusersaresubjecttotheSunMicrosystems,Inc.standardlicenseagreementandapplicableprovisions oftheFARanditssupplements. Thisdistributionmayincludematerialsdevelopedbythirdparties. PartsoftheproductmaybederivedfromBerkeleyBSDsystems,licensedfromtheUniversityofCalifornia.UNIXisaregisteredtrademarkintheU.S.andother countries,exclusivelylicensedthroughX/OpenCompany,Ltd. Sun,SunMicrosystems,theSunlogo,theSolarislogo,theJavaCoffeeCuplogo,docs.sun.com,ClusterToolsJava,andSolarisaretrademarksorregistered trademarksofSunMicrosystems,Inc.oritssubsidiariesintheU.S.andothercountries.AllSPARCtrademarksareusedunderlicenseandaretrademarksor registeredtrademarksofSPARCInternational,Inc.intheU.S.andothercountries.ProductsbearingSPARCtrademarksarebaseduponanarchitecturedeveloped bySunMicrosystems,Inc. TheOPENLOOKandSunTMGraphicalUserInterfacewasdevelopedbySunMicrosystems,Inc.foritsusersandlicensees.Sunacknowledgesthepioneeringefforts ofXeroxinresearchinganddevelopingtheconceptofvisualorgraphicaluserinterfacesforthecomputerindustry.Sunholdsanon-exclusivelicensefromXeroxto theXeroxGraphicalUserInterface,whichlicensealsocoversSun'slicenseeswhoimplementOPENLOOKGUIsandotherwisecomplywithSun'swrittenlicense agreements. ProductscoveredbyandinformationcontainedinthispublicationarecontrolledbyU.S.ExportControllawsandmaybesubjecttotheexportorimportlawsin othercountries.Nuclear,missile,chemicalorbiologicalweaponsornuclearmaritimeendusesorendusers,whetherdirectorindirect,arestrictlyprohibited.Export orreexporttocountriessubjecttoU.S.embargoortoentitiesidentifiedonU.S.exportexclusionlists,including,butnotlimitedto,thedeniedpersonsandspecially designatednationalslistsisstrictlyprohibited. DOCUMENTATIONISPROVIDED“ASIS”ANDALLEXPRESSORIMPLIEDCONDITIONS,REPRESENTATIONSANDWARRANTIES,INCLUDINGANY IMPLIEDWARRANTYOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEORNON-INFRINGEMENT,AREDISCLAIMED,EXCEPTTO THEEXTENTTHATSUCHDISCLAIMERSAREHELDTOBELEGALLYINVALID. Copyright2008SunMicrosystems,Inc. 4150NetworkCircle,SantaClara,CA95054U.S.A. Tousdroitsréservés. SunMicrosystems,Inc.détientlesdroitsdepropriétéintellectuellerelatifsàlatechnologieincorporéedansleproduitquiestdécritdanscedocument.Enparticulier, etcesanslimitation,cesdroitsdepropriétéintellectuellepeuventinclureunouplusieursbrevetsaméricainsoudesapplicationsdebrevetenattenteauxEtats-Unis etdansd'autrespays. Cettedistributionpeutcomprendredescomposantsdéveloppéspardestiercespersonnes. CertainescomposantsdeceproduitpeuventêtredérivéesdulogicielBerkeleyBSD,licenciésparl'UniversitédeCalifornie.UNIXestunemarquedéposéeaux Etats-Unisetdansd'autrespays;elleestlicenciéeexclusivementparX/OpenCompany,Ltd. Sun,SunMicrosystems,lelogoSun,lelogoSolaris,lelogoJavaCoffeeCup,docs.sun.com,ClusterToolsJavaetSolarissontdesmarquesdefabriqueoudesmarques déposéesdeSunMicrosystems,Inc.,ousesfiliales,auxEtats-Unisetdansd'autrespays.TouteslesmarquesSPARCsontutiliséessouslicenceetsontdesmarquesde fabriqueoudesmarquesdéposéesdeSPARCInternational,Inc.auxEtats-Unisetdansd'autrespays.LesproduitsportantlesmarquesSPARCsontbaséssurune architecturedéveloppéeparSunMicrosystems,Inc. L'interfaced'utilisationgraphiqueOPENLOOKetSunaétédéveloppéeparSunMicrosystems,Inc.poursesutilisateursetlicenciés.Sunreconnaîtleseffortsde pionniersdeXeroxpourlarechercheetledéveloppementduconceptdesinterfacesd'utilisationvisuelleougraphiquepourl'industriedel'informatique.Sundétient unelicencenonexclusivedeXeroxsurl'interfaced'utilisationgraphiqueXerox,cettelicencecouvrantégalementleslicenciésdeSunquimettentenplacel'interface d'utilisationgraphiqueOPENLOOKetqui,enoutre,seconformentauxlicencesécritesdeSun. Lesproduitsquifontl'objetdecettepublicationetlesinformationsqu'ilcontientsontrégisparlalegislationaméricaineenmatièredecontrôledesexportationset peuventêtresoumisaudroitd'autrespaysdansledomainedesexportationsetimportations.Lesutilisationsfinales,ouutilisateursfinaux,pourdesarmesnucléaires, desmissiles,desarmeschimiquesoubiologiquesoupourlenucléairemaritime,directementouindirectement,sontstrictementinterdites.Lesexportationsou réexportationsversdespayssousembargodesEtats-Unis,ouversdesentitésfigurantsurleslistesd'exclusiond'exportationaméricaines,ycompris,maisdemanière nonexclusive,lalistedepersonnesquifontobjetd'unordredenepasparticiper,d'unefaçondirecteouindirecte,auxexportationsdesproduitsoudesservicesqui sontrégisparlalegislationaméricaineenmatièredecontrôledesexportationsetlalistederessortissantsspécifiquementdesignés,sontrigoureusementinterdites. LADOCUMENTATIONESTFOURNIE"ENL'ETAT"ETTOUTESAUTRESCONDITIONS,DECLARATIONSETGARANTIESEXPRESSESOUTACITES SONTFORMELLEMENTEXCLUES,DANSLAMESUREAUTORISEEPARLALOIAPPLICABLE,YCOMPRISNOTAMMENTTOUTEGARANTIE IMPLICITERELATIVEALAQUALITEMARCHANDE,AL'APTITUDEAUNEUTILISATIONPARTICULIEREOUAL'ABSENCEDECONTREFACON. 080829@20795 Contents Preface...................................................................................................................................................13 1 CoveringMultithreadingBasics........................................................................................................17 MultithreadingTerms.........................................................................................................................17 SolarisMultithreadingLibrariesandStandards..............................................................................19 BenefitingFromMultithreading .......................................................................................................20 ImprovingApplicationResponsiveness....................................................................................20 UsingMultiprocessorsEfficiently..............................................................................................20 ImprovingProgramStructure....................................................................................................20 UsingFewerSystemResources ..................................................................................................21 CombiningThreadsandRPC ....................................................................................................21 MultithreadingConcepts ...................................................................................................................22 ConcurrencyandParallelism .....................................................................................................22 MultithreadingStructure ............................................................................................................22 ThreadScheduling.......................................................................................................................23 ThreadCancellation ....................................................................................................................24 ThreadSynchronization .............................................................................................................24 Usingthe64-bitArchitecture ............................................................................................................25 2 BasicThreadsProgramming..............................................................................................................27 LifecycleofaThread ...........................................................................................................................27 ThePthreadsLibrary ..........................................................................................................................28 CreatingaDefaultThread ..........................................................................................................28 WaitingforThreadTermination...............................................................................................30 SimpleThreadsExample.............................................................................................................31 DetachingaThread .....................................................................................................................32 CreatingaKeyforThread-SpecificData...................................................................................33 3 Contents DeletingtheThread-SpecificDataKey .....................................................................................34 SettingThread-SpecificData......................................................................................................35 GettingThread-SpecificData.....................................................................................................36 GlobalandPrivateThread-SpecificDataExample..................................................................37 GettingtheThreadIdentifier......................................................................................................39 ComparingThreadIDs...............................................................................................................39 CallinganInitializationRoutineforaThread..........................................................................40 YieldingThreadExecution.........................................................................................................41 SettingtheThreadPolicyandSchedulingParameters............................................................41 GettingtheThreadPolicyandSchedulingParameters...........................................................42 SettingtheThreadPriority .........................................................................................................43 SendingaSignaltoaThread.......................................................................................................43 AccessingtheSignalMaskoftheCallingThread.....................................................................44 ForkingSafely...............................................................................................................................45 TerminatingaThread .................................................................................................................45 FinishingUp .................................................................................................................................46 CancelaThread............................................................................................................................46 CancellingaThread.....................................................................................................................48 EnablingorDisablingCancellation...........................................................................................48 SettingCancellationType...........................................................................................................49 CreatingaCancellationPoint.....................................................................................................50 PushingaHandlerOntotheStack .............................................................................................50 PullingaHandlerOfftheStack ..................................................................................................51 3 ThreadAttributes ................................................................................................................................53 AttributeObject...................................................................................................................................53 InitializingAttributes ..................................................................................................................54 DestroyingAttributes..................................................................................................................56 SettingDetachState .....................................................................................................................56 GettingtheDetachState..............................................................................................................57 SettingtheStackGuardSize .......................................................................................................58 GettingtheStackGuardSize ......................................................................................................59 SettingtheScope ..........................................................................................................................60 GettingtheScope .........................................................................................................................61 SettingtheThreadConcurrencyLevel......................................................................................61 4 MultithreadedProgrammingGuide • September2008 Contents GettingtheThreadConcurrencyLevel.....................................................................................62 SettingtheSchedulingPolicy......................................................................................................62 GettingtheSchedulingPolicy ....................................................................................................63 SettingtheInheritedSchedulingPolicy ....................................................................................64 GettingtheInheritedSchedulingPolicy ...................................................................................65 SettingtheSchedulingParameters.............................................................................................65 GettingtheSchedulingParameters ...........................................................................................66 AboutStacks .................................................................................................................................68 SettingtheStackSize ...................................................................................................................69 GettingtheStackSize ..................................................................................................................70 SettingtheStackAddressandSize.............................................................................................71 GettingtheStackAddressandSize............................................................................................72 4 ProgrammingwithSynchronizationObjects.................................................................................73 MutualExclusionLockAttributes.....................................................................................................74 InitializingaMutexAttributeObject.........................................................................................75 DestroyingaMutexAttributeObject ........................................................................................76 SettingtheScopeofaMutex .......................................................................................................77 GettingtheScopeofaMutex......................................................................................................78 SettingtheMutexTypeAttribute...............................................................................................78 GettingtheMutexTypeAttribute..............................................................................................79 SettingtheMutexAttribute'sProtocol ......................................................................................80 GettingtheMutexAttribute'sProtocol .....................................................................................82 SettingtheMutexAttribute'sPriorityCeiling..........................................................................82 GettingtheMutexAttribute'sPriorityCeiling.........................................................................83 SettingtheMutex'sPriorityCeiling...........................................................................................84 GettingtheMutex'sPriorityCeiling..........................................................................................85 SettingtheMutex'sRobustAttribute.........................................................................................85 GettingtheMutex'sRobustAttribute........................................................................................87 UsingMutualExclusionLocks ..........................................................................................................87 InitializingaMutex......................................................................................................................88 MakingaMutexConsistent........................................................................................................89 LockingaMutex...........................................................................................................................90 UnlockingaMutex ......................................................................................................................92 LockingaMutexWithoutBlocking...........................................................................................93 5 Contents LockingaMutexBeforeaSpecifiedAbsoluteTime.................................................................94 LockingaMutexWithinaSpecifiedTimeInterval .................................................................95 DestroyingaMutex......................................................................................................................95 CodeExamplesofMutexLocking .............................................................................................96 UsingSpinLocks ...............................................................................................................................101 InitializingaSpinLock..............................................................................................................101 AcquiringaSpinLock ...............................................................................................................102 AcquiringaNon-BlockingSpinLock......................................................................................103 UnlockingaSpinLock ..............................................................................................................103 DestroyingaSpinLock .............................................................................................................104 ConditionVariableAttributes.........................................................................................................105 InitializingaConditionVariableAttribute ............................................................................106 RemovingaConditionVariableAttribute..............................................................................107 SettingtheScopeofaConditionVariable ..............................................................................107 GettingtheScopeofaConditionVariable .............................................................................108 SettingtheClockSelectionConditionVariable.....................................................................109 GettingtheClockSelectionConditionVariable....................................................................110 UsingConditionVariables...............................................................................................................110 InitializingaConditionVariable .............................................................................................111 BlockingonaConditionVariable ...........................................................................................112 UnblockingOneThread ...........................................................................................................113 BlockingUntilaSpecifiedTime...............................................................................................115 BlockingForaSpecifiedInterval..............................................................................................116 UnblockingAllThreads............................................................................................................117 DestroyingtheConditionVariableState................................................................................119 LostWake-UpProblem ............................................................................................................119 ProducerandConsumerProblem...........................................................................................120 SynchronizationWithSemaphores ................................................................................................123 NamedandUnnamedSemaphores.........................................................................................124 CountingSemaphoresOverview .............................................................................................125 InitializingaSemaphore ...........................................................................................................125 IncrementingaSemaphore.......................................................................................................127 BlockingonaSemaphoreCount..............................................................................................128 DecrementingaSemaphoreCount .........................................................................................128 DestroyingtheSemaphoreState ..............................................................................................129 ProducerandConsumerProblemUsingSemaphores .........................................................130 6 MultithreadedProgrammingGuide • September2008 Contents Read-WriteLockAttributes.............................................................................................................131 InitializingaRead-WriteLockAttribute ................................................................................132 DestroyingaRead-WriteLockAttribute................................................................................132 SettingaRead-WriteLockAttribute .......................................................................................133 GettingaRead-WriteLockAttribute ......................................................................................133 UsingRead-WriteLocks ..................................................................................................................134 InitializingaRead-WriteLock .................................................................................................134 AcquiringtheReadLockonRead-WriteLock ......................................................................135 AcquiringaReadLockonaRead-WriteLockBeforeaSpecifiedAbsoluteTime .............136 AcquiringaNon-BlockingReadLockonaRead-WriteLock..............................................137 AcquiringtheWriteLockonaRead-WriteLock ..................................................................138 AcquiringaNon-blockingWriteLockonaRead-WriteLock ............................................139 AcquiringaWriteLockonaRead-WriteLockBeforeaSpecifiedAbsoluteTime............139 UnlockingaRead-WriteLock..................................................................................................140 DestroyingaRead-WriteLock.................................................................................................141 UsingBarrierSynchronization........................................................................................................142 InitializingaSynchronizationBarrier.....................................................................................142 WaitingforThreadstoSynchronizeataBarrier ...................................................................143 DestroyingaSynchronizationBarrier.....................................................................................144 InitializingaBarrierAttributesObject....................................................................................144 SettingaBarrierProcess-SharedAttribute .............................................................................145 GettingaBarrierProcess-SharedAttribute............................................................................145 DestroyingaBarrierAttributesObject ...................................................................................146 SynchronizationAcrossProcessBoundaries.................................................................................147 ProducerandConsumerProblemExample...........................................................................147 ComparingPrimitives ......................................................................................................................148 5 ProgrammingWiththeSolarisSoftware.......................................................................................151 ForkingIssuesinProcessCreation..................................................................................................151 Fork-OneModel ........................................................................................................................152 Fork-AllModel...........................................................................................................................155 ChoosingtheRightFork ...........................................................................................................155 ProcessCreation:execandexitIssues..........................................................................................155 Timers,Alarms,andProfiling..........................................................................................................156 Timers .........................................................................................................................................156 7 Contents Alarms .........................................................................................................................................156 ProfilingaMultithreadedProgram .........................................................................................156 NonlocalGoto:setjmpandlongjmp ..............................................................................................156 ResourceLimits .................................................................................................................................157 LWPsandSchedulingClasses..........................................................................................................157 TimeshareScheduling...............................................................................................................158 RealtimeScheduling ..................................................................................................................158 FairShareScheduling ................................................................................................................159 FixedPriorityScheduling..........................................................................................................159 ExtendingTraditionalSignals .........................................................................................................159 SynchronousSignals..................................................................................................................160 AsynchronousSignals ...............................................................................................................160 ContinuationSemantics ...........................................................................................................161 OperationsonSignals................................................................................................................162 Thread-DirectedSignals ...........................................................................................................163 CompletionSemantics ..............................................................................................................164 SignalHandlersandAsync-SignalSafety................................................................................166 InterruptedWaitsonConditionVariables.............................................................................168 I/OIssues............................................................................................................................................168 I/OasaRemoteProcedureCall ...............................................................................................168 TamedAsynchrony ...................................................................................................................169 AsynchronousI/O .....................................................................................................................169 SharedI/OandNewI/OSystemCalls.....................................................................................170 Alternativestogetcandputc ..................................................................................................171 6 ProgrammingWithSolarisThreads................................................................................................173 ComparingAPIsforSolarisThreadsandPOSIXThreads...........................................................173 MajorAPIDifferences...............................................................................................................174 FunctionComparisonTable.....................................................................................................174 UniqueSolarisThreadsFunctions ..................................................................................................178 SuspendingThreadExecution .................................................................................................178 ContinuingaSuspendedThread .............................................................................................179 SimilarSynchronizationFunctions—Read-WriteLocks.............................................................180 InitializeaRead-WriteLock.....................................................................................................180 AcquiringaReadLock ..............................................................................................................181 8 MultithreadedProgrammingGuide • September2008