Multithreaded Programming Guide
Total Page:16
File Type:pdf, Size:1020Kb
Multithreaded Programming Guide Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054 U.S.A. Part No: 806–6867–10 May 2002 Copyright 2002 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. All rights reserved. This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Third-party software, including font technology, is copyrighted and licensed from Sun suppliers. Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd. Sun, Sun Microsystems, the Sun logo, docs.sun.com, AnswerBook, AnswerBook2, and Solaris are trademarks, registered trademarks, or service marks of Sun Microsystems, Inc. in the U.S. and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc. The OPEN LOOK and Sun™ Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written license agreements. Federal Acquisitions: Commercial Software–Government Users Subject to Standard License Terms and Conditions. DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. Copyright 2002 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. Tous droits réservés Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a. Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun. Des parties de ce produit pourront être dérivées du système Berkeley BSD licenciés par l’Université de Californie. UNIX est une marque déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company, Ltd. Sun, Sun Microsystems, le logo Sun, docs.sun.com, AnswerBook, AnswerBook2, et Solaris sont des marques de fabrique ou des marques déposées, ou marques de service, de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays. Toutes les marques SPARC sont utilisées sous licence et sont des marques de fabrique ou des marques déposées de SPARC International, Inc. aux Etats-Unis et dans d’autres pays. Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc. L’interface d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour la recherche et le développement du concept des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent en place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun. CETTE PUBLICATION EST FOURNIE “EN L’ETAT” ET AUCUNE GARANTIE, EXPRESSE OU IMPLICITE, N’EST ACCORDEE, Y COMPRIS DES GARANTIES CONCERNANT LA VALEUR MARCHANDE, L’APTITUDE DE LA PUBLICATION A REPONDRE A UNE UTILISATION PARTICULIERE, OU LE FAIT QU’ELLE NE SOIT PAS CONTREFAISANTE DE PRODUIT DE TIERS. CE DENI DE GARANTIE NE S’APPLIQUERAIT PAS, DANS LA MESURE OU IL SERAIT TENU JURIDIQUEMENT NUL ET NON AVENU. 020115@3062 Contents Preface 11 1 Covering Multithreading Basics 15 Defining Multithreading Terms 15 Meeting Multithreading Standards 17 Benefiting From Multithreading 17 Improving Application Responsiveness 17 Using Multiprocessors Efficiently 17 Improving Program Structure 18 Using Fewer System Resources 18 Combining Threads and RPC 18 Understanding Basic Multithreading Concepts 18 Concurrency and Parallelism 18 Looking at Multithreading Structure 19 Scheduling 21 Cancellation 22 Synchronization 22 Using the 64–bit Architecture 23 2 Basic Threads Programming 25 The Threads Library 25 Create a Default Thread 26 Wait for Thread Termination 27 A Simple Threads Example 28 Detaching a Thread 29 3 Create a Key for Thread-Specific Data 30 Delete the Thread-Specific Data Key 31 Set Thread-Specific Data 32 Get Thread-Specific Data 33 Get the Thread Identifier 36 Compare Thread IDs 36 Initializing Threads 37 Yield Thread Execution 37 Set the Thread Priority 38 Get the Thread Priority 39 Send a Signal to a Thread 39 Access the Signal Mask of the Calling Thread 40 Forking Safely 41 Terminate a Thread 41 Finishing Up 42 Cancellation 43 Cancel a Thread 44 Enable or Disable Cancellation 45 Set Cancellation Type 45 Create a Cancellation Point 46 Push a Handler Onto the Stack 47 Pull a Handler Off the Stack 47 3 Thread Create Attributes 49 Attributes 50 Initialize Attributes 50 Destroy Attributes 52 Set Detach State 52 Get Detach State 53 Set Stack Guard Size 54 Get Stack Guard Size 55 Set Scope 56 Get Scope 57 Set Thread Concurrency Level 57 Get Thread Concurrency Level 58 Set Scheduling Policy 58 Get Scheduling Policy 59 4 Multithreaded Programming Guide • May 2002 Set Inherited Scheduling Policy 60 Get Inherited Scheduling Policy 61 Set Scheduling Parameters 61 Get Scheduling Parameters 62 Set Stack Size 64 Get Stack Size 65 About Stacks 65 Set Stack Address 67 Get Stack Address 68 4 Programming with Synchronization Objects 69 Mutual Exclusion Lock Attributes 70 Initialize a Mutex Attribute Object 72 Destroy a Mutex Attribute Object 72 Set the Scope of a Mutex 73 Get the Scope of a Mutex 74 Set the Mutex Type Attribute 75 Get the Mutex Type Attribute 76 Set Mutex Attribute’s Protocol 76 Get Mutex Attribute’s Protocol 79 Set Mutex Attribute’s Priority Ceiling 79 Get Mutex Attribute’s Priority Ceiling 80 Set Mutex’s Priority Ceiling 82 Get Mutex’s Priority Ceiling 83 Set Mutex’s Robust Attribute 83 Get Mutex’s Robust Attribute 85 Using Mutual Exclusion Locks 86 Initialize a Mutex 87 Make Mutex Consistent 88 Lock a Mutex 89 Unlock a Mutex 91 Lock With a Nonblocking Mutex 92 Destroy a Mutex 93 Mutex Lock Code Examples 94 Condition Variable Attributes 98 Initialize a Condition Variable Attribute 99 Remove a Condition Variable Attribute 100 Contents 5 Set the Scope of a Condition Variable 101 Get the Scope of a Condition Variable 102 Using Condition Variables 102 Initialize a Condition Variable 103 Block on a Condition Variable 104 Unblock One Thread 105 Block Until a Specified Time 107 Block For a Specified Interval 108 Unblock All Threads 109 Destroy Condition Variable State 110 The Lost Wake-Up Problem 111 The Producer/Consumer Problem 111 Semaphores 114 Counting Semaphores 116 Initialize a Semaphore 116 Named Semaphores 118 Increment a Semaphore 118 Block on a Semaphore Count 119 Decrement a Semaphore Count 119 Destroy the Semaphore State 120 The Producer/Consumer Problem, Using Semaphores 121 Read-Write Lock Attributes 122 Initialize a Read-Write Lock Attribute 123 Destroy a Read-Write Lock Attribute 123 Set a Read-Write Lock Attribute 124 Get a Read-Write Lock Attribute 125 Using Read-Write Locks 125 Initialize a Read-Write Lock 126 Read Lock on Read-Write Lock 127 Read Lock With a Nonblocking Read-Write Lock 128 Write Lock on Read-Write Lock 128 Write Lock With a Nonblocking Read-Write Lock 129 Unlock a Read-Write Lock 129 Destroy a Read-Write Lock 130 Synchronization Across Process Boundaries 131 Producer/Consumer Problem Example 131 Interprocess Locking Without the Threads Library 133 Comparing Primitives 133 6 Multithreaded Programming Guide • May 2002 5 Programming With the Operating Environment 135 Process Creation—Forking Issues 135 The Fork-One Model 136 The Fork-All Model 139 Choosing the Right Fork 139 Process Creation—exec(2) and exit(2) Issues 139 Timers, Alarms, and Profiling 140 Per-LWP POSIX Timers 140 Per-Thread Alarms 141 Profiling 141 Nonlocal Goto—setjmp(3C) and longjmp(3C) 142 Resource Limits 142 LWPs and Scheduling Classes 142 Timeshare Scheduling 143 Realtime Scheduling 143 Fair Share Scheduling 144 Fixed Priority Scheduling 144 Extending Traditional Signals 145 Synchronous Signals 146 Asynchronous Signals 146 Continuation Semantics 146 Operations on Signals 147 Thread-Directed Signals 149 Completion Semantics 150 Signal Handlers and Async-Signal Safety 151 Interrupted Waits on Condition Variables 153 I/O Issues 154 I/O as a Remote Procedure Call 154 Tamed Asynchrony 155 Asynchronous I/O 155 Shared I/O and New