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: 816–5137–10 January 2005 Copyright 2005 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 or registered trademarks 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. U.S. Government Rights – Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. 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 2005 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, 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. 040915@9495 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 18 Improving Program Structure 18 Using Fewer System Resources 18 Combining Threads and RPC 18 Multithreading Concepts 19 Concurrency and Parallelism 19 Looking at Multithreading Structure 19 Thread Scheduling 20 Thread Cancellation 20 Thread Synchronization 21 Using the 64-bit Architecture 21 2 Basic Threads Programming 23 The Threads Library 23 Creating a Default Thread 23 Waiting for Thread Termination 25 Simple Threads Example 26 Detaching a Thread 27 Creating a Key for Thread-Specific Data 28 3 Deleting the Thread-Specific Data Key 29 Setting Thread-Specific Data 30 Getting Thread-Specific Data 30 Getting the Thread Identifier 33 Comparing Thread IDs 34 Initializing Threads 34 Yielding Thread Execution 35 Setting the Thread Priority 35 Getting the Thread Priority 36 Sending a Signal to a Thread 37 Accessing the Signal Mask of the Calling Thread 37 Forking Safely 38 Terminating a Thread 39 Finishing Up 39 Cancel a Thread 40 Cancelling a Thread 41 Enabling or Disabling Cancellation 42 Setting Cancellation Type 43 Creating a Cancellation Point 43 Pushing a Handler Onto the Stack 44 Pulling a Handler Off the Stack 44 3 Thread Attributes 47 Attribute Object 47 Initializing Attributes 48 Destroying Attributes 49 Setting Detach State 50 Getting the Detach State 51 Setting the Stack Guard Size 52 Getting the Stack Guard Size 53 Setting the Scope 53 Getting the Scope 54 Setting the Thread Concurrency Level 55 Getting the Thread Concurrency Level 55 Setting the Scheduling Policy 56 Getting the Scheduling Policy 57 Setting the Inherited Scheduling Policy 58 Getting the Inherited Scheduling Policy 58 4 Multithreaded Programming Guide • January 2005 Setting the Scheduling Parameters 59 Getting the Scheduling Parameters 60 Setting the Stack Size 61 Getting the Stack Size 62 About Stacks 63 Setting the Stack Address and Size 64 Getting the Stack Address and Size 65 4 Programming with Synchronization Objects 67 Mutual Exclusion Lock Attributes 68 Initializing a Mutex Attribute Object 70 Destroying a Mutex Attribute Object 70 Setting the Scope of a Mutex 71 Getting the Scope of a Mutex 72 Setting the Mutex Type Attribute 72 Getting the Mutex Type Attribute 74 Setting the Mutex Attribute’s Protocol 74 Getting the Mutex Attribute’s Protocol 76 Setting the Mutex Attribute’s Priority Ceiling 77 Getting the Mutex Attribute’s Priority Ceiling 78 Setting the Mutex’s Priority Ceiling 79 Getting the Mutex’s Priority Ceiling 80 Setting the Mutex’s Robust Attribute 81 Getting the Mutex’s Robust Attribute 83 Using Mutual Exclusion Locks 84 Initializing a Mutex 84 Making a Mutex Consistent 86 Locking a Mutex 87 Unlocking a Mutex 88 Locking With a Nonblocking Mutex 89 Destroying a Mutex 91 Code Examples of Mutex Locking 91 Condition Variable Attributes 95 Initializing a Condition Variable Attribute 96 Removing a Condition Variable Attribute 97 Setting the Scope of a Condition Variable 98 Getting the Scope of a Condition Variable 99 Using Condition Variables 100 5 Initializing a Condition Variable 100 Blocking on a Condition Variable 101 Unblocking One Thread 103 Blocking Until a Specified Time 104 Blocking For a Specified Interval 105 Unblocking All Threads 106 Destroying the Condition Variable State 108 Lost Wake-Up Problem 108 Producer and Consumer Problem 109 Synchronization With Semaphores 111 Named and Unnamed Semaphores 113 Counting Semaphores Overview 113 Initializing a Semaphore 114 Incrementing a Semaphore 115 Blocking on a Semaphore Count 116 Decrementing a Semaphore Count 117 Destroying the Semaphore State 117 Producer and Consumer Problem Using Semaphores 118 Read-Write Lock Attributes 119 Initializing a Read-Write Lock Attribute 120 Destroying a Read-Write Lock Attribute 121 Setting a Read-Write Lock Attribute 121 Getting a Read-Write Lock Attribute 122 Using Read-Write Locks 123 Initializing a Read-Write Lock 123 Acquiring the Read Lock on Read-Write Lock 124 Reading a Lock With a Nonblocking Read-Write Lock 125 Writing a Lock on Read-Write Lock 125 Writing a Lock With a Nonblocking Read-Write Lock 126 Unlocking a Read-Write Lock 127 Destroying a Read-Write Lock 128 Synchronization Across Process Boundaries 129 Producer and Consumer Problem Example 129 Comparing Primitives 130 5 Programming With the Solaris Software 133 Forking Issues in Process Creation 133 Fork-One Model 134 6 Multithreaded Programming Guide • January 2005 Fork-All Model 136 Choosing the Right Fork 137 Process Creation: exec and exit Issues 137 Timers, Alarms, and Profiling 138 Per-LWP POSIX Timers 138 Per-Thread Alarms 139 Profiling a Multithreaded Program 139 Nonlocal Goto: setjmp and longjmp 140 Resource Limits 140 LWPs and Scheduling Classes 140 Timeshare Scheduling 141