* better
[mascara-docs.git] / lang / C / web / threads / posix.thread.programming
blobba9836c1a37d3ea0e9151e7a195fa679e49ae337
2 POSIX Threads Programming
4 Author: Blaise Barney, Lawrence Livermore National Laboratory                                                     UCRL-MI-133316
6 Table of Contents
8  1. Abstract
9  2. Pthreads Overview
10      1. What is a Thread?
11      2. What are Pthreads?
12      3. Why Pthreads?
13      4. Designing Threaded Programs
14  3. The Pthreads API
15  4. Compiling Threaded Programs
16  5. Thread Management
17      1. Creating and Terminating Threads
18      2. Passing Arguments to Threads
19      3. Joining and Detaching Threads
20      4. Stack Management
21      5. Miscellaneous Routines
22  6. Mutex Variables
23      1. Mutex Variables Overview
24      2. Creating and Destroying Mutexes
25      3. Locking and Unlocking Mutexes
26  7. Condition Variables
27      1. Condition Variables Overview
28      2. Creating and Destroying Condition Variables
29      3. Waiting and Signaling on Condition Variables
30  8. LLNL Specific Information and Recommendations
31  9. Topics Not Covered
32 10. Pthread Library Routines Reference
33 11. References and More Information
34 12. Exercise
38 ┌─────────────────────────────────────────────────────────────────────────────┐
39 │ Abstract                                                                    │
40 └─────────────────────────────────────────────────────────────────────────────┘
43 In shared memory multiprocessor architectures, such as SMPs, threads can be
44 used to implement parallelism. Historically, hardware vendors have implemented
45 their own proprietary versions of threads, making portability a concern for
46 software developers. For UNIX systems, a standardized C language threads
47 programming interface has been specified by the IEEE POSIX 1003.1c standard.
48 Implementations that adhere to this standard are referred to as POSIX threads,
49 or Pthreads.
51 The tutorial begins with an introduction to concepts, motivations, and design
52 considerations for using Pthreads. Each of the three major classes of routines
53 in the Pthreads API are then covered: Thread Management, Mutex Variables, and
54 Condition Variables. Example codes are used throughout to demonstrate how to
55 use most of the Pthreads routines needed by a new Pthreads programmer. The
56 tutorial concludes with a discussion of LLNL specifics and how to mix MPI with
57 pthreads. A lab exercise, with numerous example codes (C Language) is also
58 included.
60 Level/Prerequisites: Ideal for those who are new to parallel programming with
61 threads. A basic understanding of parallel programming in C is assumed. For
62 those who are unfamiliar with Parallel Programming in general, the material
63 covered in EC3500: Introduction To Parallel Computing would be helpful.
67 ┌─────────────────────────────────────────────────────────────────────────────┐
68 │ Pthreads Overview                                                           │
69 └─────────────────────────────────────────────────────────────────────────────┘
71 What is a Thread?
73   • Technically, a thread is defined as an independent stream of instructions
74     that can be scheduled to run as such by the operating system. But what does
75     this mean?
77   • To the software developer, the concept of a "procedure" that runs
78     independently from its main program may best describe a thread.
80   • To go one step further, imagine a main program (a.out) that contains a
81     number of procedures. Then imagine all of these procedures being able to be
82     scheduled to run simultaneously and/or independently by the operating
83     system. That would describe a "multi-threaded" program.
85   • How is this accomplished?
87   • Before understanding a thread, one first needs to understand a UNIX
88     process. A process is created by the operating system, and requires a fair
89     amount of "overhead". Processes contain information about program resources
90     and program execution state, including:
91       □ Process ID, process group ID, user ID, and group ID
92       □ Environment
93       □ Working directory.
94       □ Program instructions
95       □ Registers
96       □ Stack
97       □ Heap
98       □ File descriptors
99       □ Signal actions
100       □ Shared libraries
101       □ Inter-process communication tools (such as message queues, pipes,
102         semaphores, or shared memory).
104     Unix Process Process-thread relationship
105     UNIX PROCESS THREADS WITHIN A UNIX PROCESS
107   • Threads use and exist within these process resources, yet are able to be
108     scheduled by the operating system and run as independent entities largely
109     because they duplicate only the bare essential resources that enable them
110     to exist as executable code.
112   • This independent flow of control is accomplished because a thread maintains
113     its own:
114       □ Stack pointer
115       □ Registers
116       □ Scheduling properties (such as policy or priority)
117       □ Set of pending and blocked signals
118       □ Thread specific data.
120   • So, in summary, in the UNIX environment a thread:
121       □ Exists within a process and uses the process resources
122       □ Has its own independent flow of control as long as its parent process
123         exists and the OS supports it
124       □ Duplicates only the essential resources it needs to be independently
125         schedulable
126       □ May share the process resources with other threads that act equally
127         independently (and dependently)
128       □ Dies if the parent process dies - or something similar
129       □ Is "lightweight" because most of the overhead has already been
130         accomplished through the creation of its process.
132   • Because threads within the same process share resources:
133       □ Changes made by one thread to shared system resources (such as closing
134         a file) will be seen by all other threads.
135       □ Two pointers having the same value point to the same data.
136       □ Reading and writing to the same memory locations is possible, and
137         therefore requires explicit synchronization by the programmer.
141 ┌─────────────────────────────────────────────────────────────────────────────┐
142 │ Pthreads Overview                                                           │
143 └─────────────────────────────────────────────────────────────────────────────┘
145 What are Pthreads?
147   • Historically, hardware vendors have implemented their own proprietary
148     versions of threads. These implementations differed substantially from each
149     other making it difficult for programmers to develop portable threaded
150     applications.
152   • In order to take full advantage of the capabilities provided by threads, a
153     standardized programming interface was required.
154       □ For UNIX systems, this interface has been specified by the IEEE POSIX
155         1003.1c standard (1995).
156       □ Implementations adhering to this standard are referred to as POSIX
157         threads, or Pthreads.
158       □ Most hardware vendors now offer Pthreads in addition to their
159         proprietary API's.
161   • The POSIX standard has continued to evolve and undergo revisions, including
162     the Pthreads specification.
164   • Some useful links:
165       □ standards.ieee.org/findstds/standard/1003.1-2008.html
166       □ www.opengroup.org/austin/papers/posix_faq.html
167       □ www.unix.org/version3/ieee_std.html
169   • Pthreads are defined as a set of C language programming types and procedure
170     calls, implemented with a pthread.h header/include file and a thread
171     library - though this library may be part of another library, such as libc,
172     in some implementations.
176 ┌─────────────────────────────────────────────────────────────────────────────┐
177 │ Pthreads Overview                                                           │
178 └─────────────────────────────────────────────────────────────────────────────┘
180 Why Pthreads?
182   • The primary motivation for using Pthreads is to realize potential program
183     performance gains.
185   • When compared to the cost of creating and managing a process, a thread can
186     be created with much less operating system overhead. Managing threads
187     requires fewer system resources than managing processes.
189     For example, the following table compares timing results for the fork()
190     subroutine and the pthread_create() subroutine. Timings reflect 50,000
191     process/thread creations, were performed with the time utility, and units
192     are in seconds, no optimization flags.
194     Note: don't expect the sytem and user times to add up to real time, because
195     these are SMP systems with multiple CPUs working on the problem at the same
196     time. At best, these are approximations run on local machines, past and
197     present.
199     ┌───────────────────────┬─────────────────────┬───────────────────┐
200     │                       │       fork()        │ pthread_create()  │
201     │       Platform        ├───────┬──────┬──────┼──────┬──────┬─────┤
202     │                       │ real  │ user │ sys  │ real │ user │ sys │
203     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
204     │ Intel 2.8 GHz Xeon    │   4.4 │  0.4 │  4.3 │  0.7 │  0.2 │ 0.5 │
205     │ 5660 (12cpus/node)    │       │      │      │      │      │     │
206     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
207     │ AMD 2.3 GHz Opteron   │  12.5 │  1.0 │ 12.5 │  1.2 │  0.2 │ 1.3 │
208     │ (16cpus/node)         │       │      │      │      │      │     │
209     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
210     │ AMD 2.4 GHz Opteron   │  17.6 │  2.2 │ 15.7 │  1.4 │  0.3 │ 1.3 │
211     │ (8cpus/node)          │       │      │      │      │      │     │
212     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
213     │ IBM 4.0 GHz POWER6    │   9.5 │  0.6 │  8.8 │  1.6 │  0.1 │ 0.4 │
214     │ (8cpus/node)          │       │      │      │      │      │     │
215     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
216     │ IBM 1.9 GHz POWER5    │  64.2 │ 30.7 │ 27.6 │  1.7 │  0.6 │ 1.1 │
217     │ p5-575 (8cpus/node)   │       │      │      │      │      │     │
218     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
219     │ IBM 1.5 GHz POWER4    │ 104.5 │ 48.6 │ 47.2 │  2.1 │  1.0 │ 1.5 │
220     │ (8cpus/node)          │       │      │      │      │      │     │
221     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
222     │ INTEL 2.4 GHz Xeon (2 │  54.9 │  1.5 │ 20.8 │  1.6 │  0.7 │ 0.9 │
223     │ cpus/node)            │       │      │      │      │      │     │
224     ├───────────────────────┼───────┼──────┼──────┼──────┼──────┼─────┤
225     │ INTEL 1.4 GHz         │  54.5 │  1.1 │ 22.2 │  2.0 │  1.2 │ 0.6 │
226     │ Itanium2 (4 cpus/     │       │      │      │      │      │     │
227     │ node)                 │       │      │      │      │      │     │
228     └───────────────────────┴───────┴──────┴──────┴──────┴──────┴─────┘
229     View source code fork_vs_thread.txt
231   • All threads within a process share the same address space. Inter-thread
232     communication is more efficient and in many cases, easier to use than
233     inter-process communication.
235   • Threaded applications offer potential performance gains and practical
236     advantages over non-threaded applications in several other ways:
237       □ Overlapping CPU work with I/O: For example, a program may have sections
238         where it is performing a long I/O operation. While one thread is
239         waiting for an I/O system call to complete, CPU intensive work can be
240         performed by other threads.
241       □ Priority/real-time scheduling: tasks which are more important can be
242         scheduled to supersede or interrupt lower priority tasks.
243       □ Asynchronous event handling: tasks which service events of
244         indeterminate frequency and duration can be interleaved. For example, a
245         web server can both transfer data from previous requests and manage the
246         arrival of new requests.
248   • The primary motivation for considering the use of Pthreads on an SMP
249     architecture is to achieve optimum performance. In particular, if an
250     application is using MPI for on-node communications, there is a potential
251     that performance could be greatly improved by using Pthreads for on-node
252     data transfer instead.
254   • For example:
255       □ MPI libraries usually implement on-node task communication via shared
256         memory, which involves at least one memory copy operation (process to
257         process).
258       □ For Pthreads there is no intermediate memory copy required because
259         threads share the same address space within a single process. There is
260         no data transfer, per se. It becomes more of a cache-to-CPU or
261         memory-to-CPU bandwidth (worst case) situation. These speeds are much
262         higher.
263       □ Some local comparisons are shown below:
265         ┌──────────────────────┬────────────────────────┬─────────────────────┐
266         │                      │   MPI Shared Memory    │ Pthreads Worst Case │
267         │       Platform       │       Bandwidth        │    Memory-to-CPU    │
268         │                      │        (GB/sec)        │      Bandwidth      │
269         │                      │                        │      (GB/sec)       │
270         ├──────────────────────┼────────────────────────┼─────────────────────┤
271         │ Intel 2.8 GHz Xeon   │                    5.6 │                  32 │
272         │ 5660                 │                        │                     │
273         ├──────────────────────┼────────────────────────┼─────────────────────┤
274         │ AMD 2.3 GHz Opteron  │                    1.8 │                 5.3 │
275         ├──────────────────────┼────────────────────────┼─────────────────────┤
276         │ AMD 2.4 GHz Opteron  │                    1.2 │                 5.3 │
277         ├──────────────────────┼────────────────────────┼─────────────────────┤
278         │ IBM 1.9 GHz POWER5   │                    4.1 │                  16 │
279         │ p5-575               │                        │                     │
280         ├──────────────────────┼────────────────────────┼─────────────────────┤
281         │ IBM 1.5 GHz POWER4   │                    2.1 │                   4 │
282         ├──────────────────────┼────────────────────────┼─────────────────────┤
283         │ Intel 2.4 GHz Xeon   │                    0.3 │                 4.3 │
284         ├──────────────────────┼────────────────────────┼─────────────────────┤
285         │ Intel 1.4 GHz        │                    1.8 │                 6.4 │
286         │ Itanium 2            │                        │                     │
287         └──────────────────────┴────────────────────────┴─────────────────────┘
291 ┌─────────────────────────────────────────────────────────────────────────────┐
292 │ Pthreads Overview                                                           │
293 └─────────────────────────────────────────────────────────────────────────────┘
295 Designing Threaded Programs
297 [arrowBulle] Parallel Programming:
299   • On modern, multi-cpu machines, pthreads are ideally suited for parallel
300     programming, and whatever applies to parallel programming in general,
301     applies to parallel pthreads programs.
303   • There are many considerations for designing parallel programs, such as:
304       □ What type of parallel programming model to use?
305       □ Problem partitioning
306       □ Load balancing
307       □ Communications
308       □ Data dependencies
309       □ Synchronization and race conditions
310       □ Memory issues
311       □ I/O issues
312       □ Program complexity
313       □ Programmer effort/costs/time
314       □ ...
316   • Covering these topics is beyond the scope of this tutorial, however
317     interested readers can obtain a quick overview in the Introduction to
318     Parallel Computing tutorial.
320   • In general though, in order for a program to take advantage of Pthreads, it
321     must be able to be organized into discrete, independent tasks which can
322     execute concurrently. For example, if routine1 and routine2 can be
323     interchanged, interleaved and/or overlapped in real time, they are
324     candidates for threading.
326                                    [concurrent]
328   • Programs having the following characteristics may be well suited for
329     pthreads:
330       □ Work that can be executed, or data that can be operated on, by multiple
331         tasks simultaneously
332       □ Block for potentially long I/O waits
333       □ Use many CPU cycles in some places but not others
334       □ Must respond to asynchronous events
335       □ Some work is more important than other work (priority interrupts)
337   • Pthreads can also be used for serial applications, to emulate parallel
338     execution. A perfect example is the typical web browser, which for most
339     people, runs on a single cpu desktop/laptop machine. Many things can
340     "appear" to be happening at the same time.
342   • Several common models for threaded programs exist:
344       □ Manager/worker: a single thread, the manager assigns work to other
345         threads, the workers. Typically, the manager handles all input and
346         parcels out work to the other tasks. At least two forms of the manager/
347         worker model are common: static worker pool and dynamic worker pool.
349       □ Pipeline: a task is broken into a series of suboperations, each of
350         which is handled in series, but concurrently, by a different thread. An
351         automobile assembly line best describes this model.
353       □ Peer: similar to the manager/worker model, but after the main thread
354         creates other threads, it participates in the work.
356 [arrowBulle] Shared Memory Model:
358   • All threads have access to the same global, shared memory
360   • Threads also have their own private data
362   • Programmers are responsible for synchronizing access (protecting) globally
363     shared data.
364                                 Shared Memory Model
366 [arrowBulle] Thread-safeness:
368   • Thread-safeness: in a nutshell, refers an application's ability to execute
369     multiple threads simultaneously without "clobbering" shared data or
370     creating "race" conditions.
372   • For example, suppose that your application creates several threads, each of
373     which makes a call to the same library routine:
374       □ This library routine accesses/modifies a global structure or location
375         in memory.
376       □ As each thread calls this routine it is possible that they may try to
377         modify this global structure/memory location at the same time.
378       □ If the routine does not employ some sort of synchronization constructs
379         to prevent data corruption, then it is not thread-safe.
381                                  threadunsafe
383   • The implication to users of external library routines is that if you aren't
384     100% certain the routine is thread-safe, then you take your chances with
385     problems that could arise.
387   • Recommendation: Be careful if your application uses libraries or other
388     objects that don't explicitly guarantee thread-safeness. When in doubt,
389     assume that they are not thread-safe until proven otherwise. This can be
390     done by "serializing" the calls to the uncertain routine, etc.
394 ┌─────────────────────────────────────────────────────────────────────────────┐
395 │ The Pthreads API                                                            │
396 └─────────────────────────────────────────────────────────────────────────────┘
399   • The original Pthreads API was defined in the ANSI/IEEE POSIX 1003.1 - 1995
400     standard. The POSIX standard has continued to evolve and undergo revisions,
401     including the Pthreads specification.
403   • Copies of the standard can be purchased from IEEE or downloaded for free
404     from other sites online.
406   • The subroutines which comprise the Pthreads API can be informally grouped
407     into four major groups:
409      1. Thread management: Routines that work directly on threads - creating,
410         detaching, joining, etc. They also include functions to set/query
411         thread attributes (joinable, scheduling etc.)
413      2. Mutexes: Routines that deal with synchronization, called a "mutex",
414         which is an abbreviation for "mutual exclusion". Mutex functions
415         provide for creating, destroying, locking and unlocking mutexes. These
416         are supplemented by mutex attribute functions that set or modify
417         attributes associated with mutexes.
419      3. Condition variables: Routines that address communications between
420         threads that share a mutex. Based upon programmer specified conditions.
421         This group includes functions to create, destroy, wait and signal based
422         upon specified variable values. Functions to set/query condition
423         variable attributes are also included.
425      4. Synchronization: Routines that manage read/write locks and barriers.
427   • Naming conventions: All identifiers in the threads library begin with
428     pthread_. Some examples are shown below.
430     ┌────────────────────┬────────────────────────────────────────────┐
431     │   Routine Prefix   │              Functional Group              │
432     ├────────────────────┼────────────────────────────────────────────┤
433     │ pthread_           │ Threads themselves and miscellaneous       │
434     │                    │ subroutines                                │
435     ├────────────────────┼────────────────────────────────────────────┤
436     │ pthread_attr_      │ Thread attributes objects                  │
437     ├────────────────────┼────────────────────────────────────────────┤
438     │ pthread_mutex_     │ Mutexes                                    │
439     ├────────────────────┼────────────────────────────────────────────┤
440     │ pthread_mutexattr_ │ Mutex attributes objects.                  │
441     ├────────────────────┼────────────────────────────────────────────┤
442     │ pthread_cond_      │ Condition variables                        │
443     ├────────────────────┼────────────────────────────────────────────┤
444     │ pthread_condattr_  │ Condition attributes objects               │
445     ├────────────────────┼────────────────────────────────────────────┤
446     │ pthread_key_       │ Thread-specific data keys                  │
447     ├────────────────────┼────────────────────────────────────────────┤
448     │ pthread_rwlock_    │ Read/write locks                           │
449     ├────────────────────┼────────────────────────────────────────────┤
450     │ pthread_barrier_   │ Synchronization barriers                   │
451     └────────────────────┴────────────────────────────────────────────┘
453   • The concept of opaque objects pervades the design of the API. The basic
454     calls work to create or modify opaque objects - the opaque objects can be
455     modified by calls to attribute functions, which deal with opaque
456     attributes.
458   • The Pthreads API contains around 100 subroutines. This tutorial will focus
459     on a subset of these - specifically, those which are most likely to be
460     immediately useful to the beginning Pthreads programmer.
462   • For portability, the pthread.h header file should be included in each
463     source file using the Pthreads library.
465   • The current POSIX standard is defined only for the C language. Fortran
466     programmers can use wrappers around C function calls. Some Fortran
467     compilers (like IBM AIX Fortran) may provide a Fortram pthreads API.
469   • A number of excellent books about Pthreads are available. Several of these
470     are listed in the References section of this tutorial.
472 ┌─────────────────────────────────────────────────────────────────────────────┐
473 │ Compiling Threaded Programs                                                 │
474 └─────────────────────────────────────────────────────────────────────────────┘
478   • Several examples of compile commands used for pthreads codes are listed in
479     the table below.
481     ┌─────────────────────┬────────────────────┬──────────────────────┐
482     │ Compiler / Platform │  Compiler Command  │     Description      │
483     ├─────────────────────┼────────────────────┼──────────────────────┤
484     │ INTEL               │ icc -pthread       │ C                    │
485     │Linux                ├────────────────────┼──────────────────────┤
486     │                     │ icpc -pthread      │ C++                  │
487     ├─────────────────────┼────────────────────┼──────────────────────┤
488     │ PathScale           │ pathcc -pthread    │ C                    │
489     │Linux                ├────────────────────┼──────────────────────┤
490     │                     │ pathCC -pthread    │ C++                  │
491     ├─────────────────────┼────────────────────┼──────────────────────┤
492     │ PGI                 │ pgcc -lpthread     │ C                    │
493     │Linux                ├────────────────────┼──────────────────────┤
494     │                     │ pgCC -lpthread     │ C++                  │
495     ├─────────────────────┼────────────────────┼──────────────────────┤
496     │ GNU                 │ gcc -pthread       │ GNU C                │
497     │Linux, BG/L, BG/P    ├────────────────────┼──────────────────────┤
498     │                     │ g++ -pthread       │ GNU C++              │
499     ├─────────────────────┼────────────────────┼──────────────────────┤
500     │                     │ bgxlc_r  /  bgcc_r │ C (ANSI  /           │
501     │ IBM                 │                    │ non-ANSI)            │
502     │BG/L and BG/P        ├────────────────────┼──────────────────────┤
503     │                     │ bgxlC_r, bgxlc++_r │ C++                  │
504     │                     ├────────────────────┼──────────────────────┤
505     └─────────────────────┴────────────────────┴──────────────────────┘
509 ┌─────────────────────────────────────────────────────────────────────────────┐
510 │ Thread Management                                                           │
511 └─────────────────────────────────────────────────────────────────────────────┘
513 Creating and Terminating Threads
515 [arrowBulle] Routines:
518     ┌─────────────────────────────────────────────────────────────────┐
519     │ pthread_create (thread,attr,start_routine,arg)                  │
520     │                                                                 │
521     │ pthread_exit (status)                                           │
522     │                                                                 │
523     │ pthread_cancel (thread)                                         │
524     │                                                                 │
525     │ pthread_attr_init (attr)                                        │
526     │                                                                 │
527     │ pthread_attr_destroy (attr)                                     │
528     └─────────────────────────────────────────────────────────────────┘
530 [arrowBulle] Creating Threads:
533   • Initially, your main() program comprises a single, default thread. All
534     other threads must be explicitly created by the programmer.
536   • pthread_create creates a new thread and makes it executable. This routine
537     can be called any number of times from anywhere within your code.
539   • pthread_create arguments:
540       □ thread: An opaque, unique identifier for the new thread returned by the
541         subroutine.
542       □ attr: An opaque attribute object that may be used to set thread
543         attributes. You can specify a thread attributes object, or NULL for the
544         default values.
545       □ start_routine: the C routine that the thread will execute once it is
546         created.
547       □ arg: A single argument that may be passed to start_routine. It must be
548         passed by reference as a pointer cast of type void. NULL may be used if
549         no argument is to be passed.
551   • The maximum number of threads that may be created by a process is
552     implementation dependent.
554   • Once created, threads are peers, and may create other threads. There is no
555     implied hierarchy or dependency between threads.
557     Peer Threads
559 [arrowBulle] Thread Attributes:
562   • By default, a thread is created with certain attributes. Some of these
563     attributes can be changed by the programmer via the thread attribute
564     object.
566   • pthread_attr_init and pthread_attr_destroy are used to initialize/destroy
567     the thread attribute object.
569   • Other routines are then used to query/set specific attributes in the thread
570     attribute object. Attributes include:
571       □ Detached or joinable state
572       □ Scheduling inheritance
573       □ Scheduling policy
574       □ Scheduling parameters
575       □ Scheduling contention scope
576       □ Stack size
577       □ Stack address
578       □ Stack guard (overflow) size
580   • Some of these attributes will be discussed later.
582 [arrowBulle] Thread Binding and Scheduling:
584    ● Question: After a thread has been created, how do you know a)when it will
585      be scheduled to run by the operating system, and b)which processor/core it
586      will run on?
587      [Answer]
589   • The Pthreads API provides several routines that may be used to specify how
590     threads are scheduled for execution. For example, threads can be scheduled
591     to run FIFO (first-in first-out), RR (round-robin) or OTHER (operating
592     system determines). It also provides the ability to set a thread's
593     scheduling priority value.
595   • These topics are not covered here, however a good overview of "how things
596     work" under Linux can be found in the sched_setscheduler man page.
598   • The Pthreads API does not provide routines for binding threads to specific
599     cpus/cores. However, local implementations may include this functionality -
600     such as providing the non-standard pthread_setaffinity_np routine. Note
601     that "_np" in the name stands for "non-portable".
603   • Also, the local operating system may provide a way to do this. For example,
604     Linux provides the sched_setaffinity routine.
606 [arrowBulle] Terminating Threads & pthread_exit():
609   • There are several ways in which a thread may be terminated:
611       □ The thread returns normally from its starting routine. It's work is
612         done.
614       □ The thread makes a call to the pthread_exit subroutine - whether its
615         work is done or not.
617       □ The thread is canceled by another thread via the pthread_cancel
618         routine.
620       □ The entire process is terminated due to making a call to either the
621         exec() or exit()
623       □ If main() finishes first, without calling pthread_exit explicitly
624         itself
626   • The pthread_exit() routine allows the programmer to specify an optional
627     termination status parameter. This optional parameter is typically returned
628     to threads "joining" the terminated thread (covered later).
630   • In subroutines that execute to completion normally, you can often dispense
631     with calling pthread_exit() - unless, of course, you want to pass the
632     optional status code back.
634   • Cleanup: the pthread_exit() routine does not close files; any files opened
635     inside the thread will remain open after the thread is terminated.
637   • Discussion on calling pthread_exit() from main():
638       □ There is a definite problem if main() finishes before the threads it
639         spawned if you don't call pthread_exit() explicitly. All of the threads
640         it created will terminate because main() is done and no longer exists
641         to support the threads.
642       □ By having main() explicitly call pthread_exit() as the last thing it
643         does, main() will block and be kept alive to support the threads it
644         created until they are done.
646 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
648 Example: Pthread Creation and Termination
650   • This simple example code creates 5 threads with the pthread_create()
651     routine. Each thread prints a "Hello World!" message, and then terminates
652     with a call to pthread_exit().
654     ┌──────────────────────────────────────────────────────────────────────────┐
655     │ ● Example Code - Pthread Creation and Termination                        │
656     │                                                                          │
657     │ #include <pthread.h>                                                     │
658     │ #include <stdio.h>                                                       │
659     │ #define NUM_THREADS     5                                                │
660     │                                                                          │
661     │ void *PrintHello(void *threadid)                                         │
662     │ {                                                                        │
663     │    long tid;                                                             │
664     │    tid = (long)threadid;                                                 │
665     │    printf("Hello World! It's me, thread #%ld!\n", tid);                  │
666     │    pthread_exit(NULL);                                                   │
667     │ }                                                                        │
668     │                                                                          │
669     │ int main (int argc, char *argv[])                                        │
670     │ {                                                                        │
671     │    pthread_t threads[NUM_THREADS];                                       │
672     │    int rc;                                                               │
673     │    long t;                                                               │
674     │    for(t=0; t<NUM_THREADS; t++){                                         │
675     │       printf("In main: creating thread %ld\n", t);                       │
676     │       rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);     │
677     │       if (rc){                                                           │
678     │          printf("ERROR; return code from pthread_create() is %d\n", rc); │
679     │          exit(-1);                                                       │
680     │       }                                                                  │
681     │    }                                                                     │
682     │                                                                          │
683     │    /* Last thing that main() should do */                                │
684     │    pthread_exit(NULL);                                                   │
685     │ }                                                                        │
686     │                                                                          │
687     │ View source code View sample output                                      │
688     └──────────────────────────────────────────────────────────────────────────┘
692 ┌─────────────────────────────────────────────────────────────────────────────┐
693 │ Thread Management                                                           │
694 └─────────────────────────────────────────────────────────────────────────────┘
696 Passing Arguments to Threads
698   • The pthread_create() routine permits the programmer to pass one argument to
699     the thread start routine. For cases where multiple arguments must be
700     passed, this limitation is easily overcome by creating a structure which
701     contains all of the arguments, and then passing a pointer to that structure
702     in the pthread_create() routine.
704   • All arguments must be passed by reference and cast to (void *).
706    ● Question: How can you safely pass data to newly created threads, given
707      their non-deterministic start-up and scheduling?
708      [Answer]
710     ┌─────────────────────────────────────────────────────────────────────────────┐
711     │ ● Example 1 - Thread Argument Passing                                       │
712     │                                                                             │
713     │     This code fragment demonstrates how to pass a simple integer to each    │
714     │     thread. The calling thread uses a unique data structure for each        │
715     │     thread, insuring that each thread's argument remains intact throughout  │
716     │     the program.                                                            │
717     │                                                                             │
718     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
719     │                                                                             │
720     │ long *taskids[NUM_THREADS];                                                 │
721     │                                                                             │
722     │ for(t=0; t<NUM_THREADS; t++)                                                │
723     │ {                                                                           │
724     │    taskids[t] = (long *) malloc(sizeof(long));                              │
725     │    *taskids[t] = t;                                                         │
726     │    printf("Creating thread %ld\n", t);                                      │
727     │    rc = pthread_create(&threads[t], NULL, PrintHello, (void *) taskids[t]); │
728     │    ...                                                                      │
729     │ }                                                                           │
730     │                                                                             │
731     │ View source code View sample output                                         │
732     └─────────────────────────────────────────────────────────────────────────────┘
734     ┌─────────────────────────────────────────────────────────────────┐
735     │ ● Example 2 - Thread Argument Passing                           │
736     │                                                                 │
737     │     This example shows how to setup/pass multiple arguments via │
738     │     a structure. Each thread receives a unique instance of the  │
739     │     structure.                                                  │
740     │                                                                 │
741     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
742     │                                                                 │
743     │ struct thread_data{                                             │
744     │    int  thread_id;                                              │
745     │    int  sum;                                                    │
746     │    char *message;                                               │
747     │ };                                                              │
748     │                                                                 │
749     │ struct thread_data thread_data_array[NUM_THREADS];              │
750     │                                                                 │
751     │ void *PrintHello(void *threadarg)                               │
752     │ {                                                               │
753     │    struct thread_data *my_data;                                 │
754     │    ...                                                          │
755     │    my_data = (struct thread_data *) threadarg;                  │
756     │    taskid = my_data->thread_id;                                 │
757     │    sum = my_data->sum;                                          │
758     │    hello_msg = my_data->message;                                │
759     │    ...                                                          │
760     │ }                                                               │
761     │                                                                 │
762     │ int main (int argc, char *argv[])                               │
763     │ {                                                               │
764     │    ...                                                          │
765     │    thread_data_array[t].thread_id = t;                          │
766     │    thread_data_array[t].sum = sum;                              │
767     │    thread_data_array[t].message = messages[t];                  │
768     │    rc = pthread_create(&threads[t], NULL, PrintHello,           │
769     │         (void *) &thread_data_array[t]);                        │
770     │    ...                                                          │
771     │ }                                                               │
772     │                                                                 │
773     │ View source code View sample output                             │
774     └─────────────────────────────────────────────────────────────────┘
776     ┌─────────────────────────────────────────────────────────────────────┐
777     │ ● Example 3 - Thread Argument Passing (Incorrect)                   │
778     │                                                                     │
779     │     This example performs argument passing incorrectly. It passes   │
780     │     the address of variable t, which is shared memory space and     │
781     │     visible to all threads. As the loop iterates, the value of this │
782     │     memory location changes, possibly before the created threads    │
783     │     can access it.                                                  │
784     │                                                                     │
785     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
786     │                                                                     │
787     │ int rc;                                                             │
788     │ long t;                                                             │
789     │                                                                     │
790     │ for(t=0; t<NUM_THREADS; t++)                                        │
791     │ {                                                                   │
792     │    printf("Creating thread %ld\n", t);                              │
793     │    rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &t); │
794     │    ...                                                              │
795     │ }                                                                   │
796     │                                                                     │
797     │ View source code View sample output                                 │
798     └─────────────────────────────────────────────────────────────────────┘
802 ┌─────────────────────────────────────────────────────────────────────────────┐
803 │ Thread Management                                                           │
804 └─────────────────────────────────────────────────────────────────────────────┘
806 Joining and Detaching Threads
808 [arrowBulle] Routines:
811     ┌─────────────────────────────────────────────────────────────────┐
812     │ pthread_join (threadid,status)                                  │
813     │                                                                 │
814     │ pthread_detach (threadid)                                       │
815     │                                                                 │
816     │ pthread_attr_setdetachstate (attr,detachstate)                  │
817     │                                                                 │
818     │ pthread_attr_getdetachstate (attr,detachstate)                  │
819     └─────────────────────────────────────────────────────────────────┘
821 [arrowBulle] Joining:
824   • "Joining" is one way to accomplish synchronization between threads. For
825     example:
827     Joining
829   • The pthread_join() subroutine blocks the calling thread until the specified
830     threadid thread terminates.
832   • The programmer is able to obtain the target thread's termination return
833     status if it was specified in the target thread's call to pthread_exit().
835   • A joining thread can match one pthread_join() call. It is a logical error
836     to attempt multiple joins on the same thread.
838   • Two other synchronization methods, mutexes and condition variables, will be
839     discussed later.
841 [arrowBulle] Joinable or Not?
844   • When a thread is created, one of its attributes defines whether it is
845     joinable or detached. Only threads that are created as joinable can be
846     joined. If a thread is created as detached, it can never be joined.
848   • The final draft of the POSIX standard specifies that threads should be
849     created as joinable.
851   • To explicitly create a thread as joinable or detached, the attr argument in
852     the pthread_create() routine is used. The typical 4 step process is:
853      1. Declare a pthread attribute variable of the pthread_attr_t data type
854      2. Initialize the attribute variable with pthread_attr_init()
855      3. Set the attribute detached status with pthread_attr_setdetachstate()
856      4. When done, free library resources used by the attribute with
857         pthread_attr_destroy()
859 [arrowBulle] Detaching:
862   • The pthread_detach() routine can be used to explicitly detach a thread even
863     though it was created as joinable.
865   • There is no converse routine.
867 [arrowBulle] Recommendations:
870   • If a thread requires joining, consider explicitly creating it as joinable.
871     This provides portability as not all implementations may create threads as
872     joinable by default.
874   • If you know in advance that a thread will never need to join with another
875     thread, consider creating it in a detached state. Some system resources may
876     be able to be freed.
878 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
880 Example: Pthread Joining
882     ┌───────────────────────────────────────────────────────────────────────┐
883     │ ● Example Code - Pthread Joining                                      │
884     │                                                                       │
885     │     This example demonstrates how to "wait" for thread completions by │
886     │     using the Pthread join routine. Since some implementations of     │
887     │     Pthreads may not create threads in a joinable state, the threads  │
888     │     in this example are explicitly created in a joinable state so     │
889     │     that they can be joined later.                                    │
890     │                                                                       │
891     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
892     │                                                                       │
893     │ #include <pthread.h>                                                  │
894     │ #include <stdio.h>                                                    │
895     │ #include <stdlib.h>                                                   │
896     │ #include <math.h>                                                     │
897     │ #define NUM_THREADS     4                                             │
898     │                                                                       │
899     │ void *BusyWork(void *t)                                               │
900     │ {                                                                     │
901     │    int i;                                                             │
902     │    long tid;                                                          │
903     │    double result=0.0;                                                 │
904     │    tid = (long)t;                                                     │
905     │    printf("Thread %ld starting...\n",tid);                            │
906     │    for (i=0; i<1000000; i++)                                          │
907     │    {                                                                  │
908     │       result = result + sin(i) * tan(i);                              │
909     │    }                                                                  │
910     │    printf("Thread %ld done. Result = %e\n",tid, result);              │
911     │    pthread_exit((void*) t);                                           │
912     │ }                                                                     │
913     │                                                                       │
914     │ int main (int argc, char *argv[])                                     │
915     │ {                                                                     │
916     │    pthread_t thread[NUM_THREADS];                                     │
917     │    pthread_attr_t attr;                                               │
918     │    int rc;                                                            │
919     │    long t;                                                            │
920     │    void *status;                                                      │
921     │                                                                       │
922     │    /* Initialize and set thread detached attribute */                 │
923     │    pthread_attr_init(&attr);                                          │
924     │    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);       │
925     │                                                                       │
926     │    for(t=0; t<NUM_THREADS; t++) {                                     │
927     │       printf("Main: creating thread %ld\n", t);                       │
928     │       rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);    │
929     │       if (rc) {                                                       │
930     │          printf("ERROR; return code from pthread_create()             │
931     │                 is %d\n", rc);                                        │
932     │          exit(-1);                                                    │
933     │          }                                                            │
934     │       }                                                               │
935     │                                                                       │
936     │    /* Free attribute and wait for the other threads */                │
937     │    pthread_attr_destroy(&attr);                                       │
938     │    for(t=0; t<NUM_THREADS; t++) {                                     │
939     │       rc = pthread_join(thread[t], &status);                          │
940     │       if (rc) {                                                       │
941     │          printf("ERROR; return code from pthread_join()               │
942     │                 is %d\n", rc);                                        │
943     │          exit(-1);                                                    │
944     │          }                                                            │
945     │       printf("Main: completed join with thread %ld having a status    │
946     │             of %ld\n",t,(long)status);                                │
947     │       }                                                               │
948     │                                                                       │
949     │ printf("Main: program completed. Exiting.\n");                        │
950     │ pthread_exit(NULL);                                                   │
951     │ }                                                                     │
952     │                                                                       │
953     │ View source code View sample output                                   │
954     └───────────────────────────────────────────────────────────────────────┘
958 ┌─────────────────────────────────────────────────────────────────────────────┐
959 │ Thread Management                                                           │
960 └─────────────────────────────────────────────────────────────────────────────┘
962 Stack Management
964 [arrowBulle] Routines:
967     ┌─────────────────────────────────────────────────────────────────┐
968     │ pthread_attr_getstacksize (attr, stacksize)                     │
969     │                                                                 │
970     │ pthread_attr_setstacksize (attr, stacksize)                     │
971     │                                                                 │
972     │ pthread_attr_getstackaddr (attr, stackaddr)                     │
973     │                                                                 │
974     │ pthread_attr_setstackaddr (attr, stackaddr)                     │
975     └─────────────────────────────────────────────────────────────────┘
977 [arrowBulle] Preventing Stack Problems:
980   • The POSIX standard does not dictate the size of a thread's stack. This is
981     implementation dependent and varies.
983   • Exceeding the default stack limit is often very easy to do, with the usual
984     results: program termination and/or corrupted data.
986   • Safe and portable programs do not depend upon the default stack limit, but
987     instead, explicitly allocate enough stack for each thread by using the
988     pthread_attr_setstacksize routine.
990   • The pthread_attr_getstackaddr and pthread_attr_setstackaddr routines can be
991     used by applications in an environment where the stack for a thread must be
992     placed in some particular region of memory.
994 [arrowBulle] Some Practical Examples at LC:
997   • Default thread stack size varies greatly. The maximum size that can be
998     obtained also varies greatly, and may depend upon the number of threads per
999     node.
1001   • Both past and present architectures are shown to demonstrate the wide
1002     variation in default thread stack size.
1004     ┌───────────────┬───────┬─────────────┬──────────────┐
1005     │     Node      │ #CPUs │ Memory (GB) │ Default Size │
1006     │ Architecture  │       │             │   (bytes)    │
1007     ├───────────────┼───────┼─────────────┼──────────────┤
1008     │ AMD Xeon 5660 │    12 │          24 │    2,097,152 │
1009     ├───────────────┼───────┼─────────────┼──────────────┤
1010     │ AMD Opteron   │     8 │          16 │    2,097,152 │
1011     ├───────────────┼───────┼─────────────┼──────────────┤
1012     │ Intel IA64    │     4 │           8 │   33,554,432 │
1013     ├───────────────┼───────┼─────────────┼──────────────┤
1014     │ Intel IA32    │     2 │           4 │    2,097,152 │
1015     ├───────────────┼───────┼─────────────┼──────────────┤
1016     │ IBM Power5    │     8 │          32 │      196,608 │
1017     ├───────────────┼───────┼─────────────┼──────────────┤
1018     │ IBM Power4    │     8 │          16 │      196,608 │
1019     ├───────────────┼───────┼─────────────┼──────────────┤
1020     │ IBM Power3    │    16 │          16 │       98,304 │
1021     └───────────────┴───────┴─────────────┴──────────────┘
1023 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1025 Example: Stack Management
1027     ┌──────────────────────────────────────────────────────────────────────────┐
1028     │ ● Example Code - Stack Management                                        │
1029     │                                                                          │
1030     │     This example demonstrates how to query and set a thread's stack      │
1031     │     size.                                                                │
1032     │                                                                          │
1033     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
1034     │                                                                          │
1035     │ #include <pthread.h>                                                     │
1036     │ #include <stdio.h>                                                       │
1037     │ #define NTHREADS 4                                                       │
1038     │ #define N 1000                                                           │
1039     │ #define MEGEXTRA 1000000                                                 │
1040     │                                                                          │
1041     │ pthread_attr_t attr;                                                     │
1042     │                                                                          │
1043     │ void *dowork(void *threadid)                                             │
1044     │ {                                                                        │
1045     │    double A[N][N];                                                       │
1046     │    int i,j;                                                              │
1047     │    long tid;                                                             │
1048     │    size_t mystacksize;                                                   │
1049     │                                                                          │
1050     │    tid = (long)threadid;                                                 │
1051     │    pthread_attr_getstacksize (&attr, &mystacksize);                      │
1052     │    printf("Thread %ld: stack size = %li bytes \n", tid, mystacksize);    │
1053     │    for (i=0; i<N; i++)                                                   │
1054     │      for (j=0; j<N; j++)                                                 │
1055     │       A[i][j] = ((i*j)/3.452) + (N-i);                                   │
1056     │    pthread_exit(NULL);                                                   │
1057     │ }                                                                        │
1058     │                                                                          │
1059     │ int main(int argc, char *argv[])                                         │
1060     │ {                                                                        │
1061     │    pthread_t threads[NTHREADS];                                          │
1062     │    size_t stacksize;                                                     │
1063     │    int rc;                                                               │
1064     │    long t;                                                               │
1065     │                                                                          │
1066     │    pthread_attr_init(&attr);                                             │
1067     │    pthread_attr_getstacksize (&attr, &stacksize);                        │
1068     │    printf("Default stack size = %li\n", stacksize);                      │
1069     │    stacksize = sizeof(double)*N*N+MEGEXTRA;                              │
1070     │    printf("Amount of stack needed per thread = %li\n",stacksize);        │
1071     │    pthread_attr_setstacksize (&attr, stacksize);                         │
1072     │    printf("Creating threads with stack size = %li bytes\n",stacksize);   │
1073     │    for(t=0; t<NTHREADS; t++){                                            │
1074     │       rc = pthread_create(&threads[t], &attr, dowork, (void *)t);        │
1075     │       if (rc){                                                           │
1076     │          printf("ERROR; return code from pthread_create() is %d\n", rc); │
1077     │          exit(-1);                                                       │
1078     │       }                                                                  │
1079     │    }                                                                     │
1080     │    printf("Created %ld threads.\n", t);                                  │
1081     │    pthread_exit(NULL);                                                   │
1082     │ }                                                                        │
1083     └──────────────────────────────────────────────────────────────────────────┘
1087 ┌─────────────────────────────────────────────────────────────────────────────┐
1088 │ Thread Management                                                           │
1089 └─────────────────────────────────────────────────────────────────────────────┘
1091 Miscellaneous Routines
1093     ┌─────────────────────────────────────────────────────────────────┐
1094     │ pthread_self ()                                                 │
1095     │                                                                 │
1096     │ pthread_equal (thread1,thread2)                                 │
1097     └─────────────────────────────────────────────────────────────────┘
1099   • pthread_self returns the unique, system assigned thread ID of the calling
1100     thread.
1102   • pthread_equal compares two thread IDs. If the two IDs are different 0 is
1103     returned, otherwise a non-zero value is returned.
1105   • Note that for both of these routines, the thread identifier objects are
1106     opaque and can not be easily inspected. Because thread IDs are opaque
1107     objects, the C language equivalence operator == should not be used to
1108     compare two thread IDs against each other, or to compare a single thread ID
1109     against another value.
1111     ┌─────────────────────────────────────────────────────────────────┐
1112     │ pthread_once (once_control, init_routine)                       │
1113     └─────────────────────────────────────────────────────────────────┘
1115   • pthread_once executes the init_routine exactly once in a process. The first
1116     call to this routine by any thread in the process executes the given
1117     init_routine, without parameters. Any subsequent call will have no effect.
1119   • The init_routine routine is typically an initialization routine.
1121   • The once_control parameter is a synchronization control structure that
1122     requires initialization prior to calling pthread_once. For example:
1124     pthread_once_t once_control = PTHREAD_ONCE_INIT;
1128 ┌─────────────────────────────────────────────────────────────────────────────┐
1129 │ Mutex Variables                                                             │
1130 └─────────────────────────────────────────────────────────────────────────────┘
1132 Overview
1134   • Mutex is an abbreviation for "mutual exclusion". Mutex variables are one of
1135     the primary means of implementing thread synchronization and for protecting
1136     shared data when multiple writes occur.
1138   • A mutex variable acts like a "lock" protecting access to a shared data
1139     resource. The basic concept of a mutex as used in Pthreads is that only one
1140     thread can lock (or own) a mutex variable at any given time. Thus, even if
1141     several threads try to lock a mutex only one thread will be successful. No
1142     other thread can own that mutex until the owning thread unlocks that mutex.
1143     Threads must "take turns" accessing protected data.
1145   • Mutexes can be used to prevent "race" conditions. An example of a race
1146     condition involving a bank transaction is shown below:
1148     ┌───────────────────────────┬───────────────────────────┬─────────┐
1149     │         Thread 1          │         Thread 2          │ Balance │
1150     ├───────────────────────────┼───────────────────────────┼─────────┤
1151     │ Read balance: $1000       │                           │ $1000   │
1152     ├───────────────────────────┼───────────────────────────┼─────────┤
1153     │                           │ Read balance: $1000       │ $1000   │
1154     ├───────────────────────────┼───────────────────────────┼─────────┤
1155     │                           │ Deposit $200              │ $1000   │
1156     ├───────────────────────────┼───────────────────────────┼─────────┤
1157     │ Deposit $200              │                           │ $1000   │
1158     ├───────────────────────────┼───────────────────────────┼─────────┤
1159     │ Update balance $1000+$200 │                           │ $1200   │
1160     ├───────────────────────────┼───────────────────────────┼─────────┤
1161     │                           │ Update balance $1000+$200 │ $1200   │
1162     └───────────────────────────┴───────────────────────────┴─────────┘
1164   • In the above example, a mutex should be used to lock the "Balance" while a
1165     thread is using this shared data resource.
1167   • Very often the action performed by a thread owning a mutex is the updating
1168     of global variables. This is a safe way to ensure that when several threads
1169     update the same variable, the final value is the same as what it would be
1170     if only one thread performed the update. The variables being updated belong
1171     to a "critical section".
1173   • A typical sequence in the use of a mutex is as follows:
1174       □ Create and initialize a mutex variable
1175       □ Several threads attempt to lock the mutex
1176       □ Only one succeeds and that thread owns the mutex
1177       □ The owner thread performs some set of actions
1178       □ The owner unlocks the mutex
1179       □ Another thread acquires the mutex and repeats the process
1180       □ Finally the mutex is destroyed
1182   • When several threads compete for a mutex, the losers block at that call -
1183     an unblocking call is available with "trylock" instead of the "lock" call.
1185   • When protecting shared data, it is the programmer's responsibility to make
1186     sure every thread that needs to use a mutex does so. For example, if 4
1187     threads are updating the same data, but only one uses a mutex, the data can
1188     still be corrupted.
1192 ┌─────────────────────────────────────────────────────────────────────────────┐
1193 │ Mutex Variables                                                             │
1194 └─────────────────────────────────────────────────────────────────────────────┘
1196 Creating and Destroying Mutexes
1198 [arrowBulle] Routines:
1201     ┌─────────────────────────────────────────────────────────────────┐
1202     │ pthread_mutex_init (mutex,attr)                                 │
1203     │                                                                 │
1204     │ pthread_mutex_destroy (mutex)                                   │
1205     │                                                                 │
1206     │ pthread_mutexattr_init (attr)                                   │
1207     │                                                                 │
1208     │ pthread_mutexattr_destroy (attr)                                │
1209     └─────────────────────────────────────────────────────────────────┘
1211 [arrowBulle] Usage:
1214   • Mutex variables must be declared with type pthread_mutex_t, and must be
1215     initialized before they can be used. There are two ways to initialize a
1216     mutex variable:
1218      1. Statically, when it is declared. For example:
1219         pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
1221      2. Dynamically, with the pthread_mutex_init() routine. This method permits
1222         setting mutex object attributes, attr.
1224     The mutex is initially unlocked.
1226   • The attr object is used to establish properties for the mutex object, and
1227     must be of type pthread_mutexattr_t if used (may be specified as NULL to
1228     accept defaults). The Pthreads standard defines three optional mutex
1229     attributes:
1230       □ Protocol: Specifies the protocol used to prevent priority inversions
1231         for a mutex.
1232       □ Prioceiling: Specifies the priority ceiling of a mutex.
1233       □ Process-shared: Specifies the process sharing of a mutex.
1235     Note that not all implementations may provide the three optional mutex
1236     attributes.
1238   • The pthread_mutexattr_init() and pthread_mutexattr_destroy() routines are
1239     used to create and destroy mutex attribute objects respectively.
1241   • pthread_mutex_destroy() should be used to free a mutex object which is no
1242     longer needed.
1246 ┌─────────────────────────────────────────────────────────────────────────────┐
1247 │ Mutex Variables                                                             │
1248 └─────────────────────────────────────────────────────────────────────────────┘
1250 Locking and Unlocking Mutexes
1252 [arrowBulle] Routines:
1255     ┌─────────────────────────────────────────────────────────────────┐
1256     │ pthread_mutex_lock (mutex)                                      │
1257     │                                                                 │
1258     │ pthread_mutex_trylock (mutex)                                   │
1259     │                                                                 │
1260     │ pthread_mutex_unlock (mutex)                                    │
1261     └─────────────────────────────────────────────────────────────────┘
1263 [arrowBulle] Usage:
1266   • The pthread_mutex_lock() routine is used by a thread to acquire a lock on
1267     the specified mutex variable. If the mutex is already locked by another
1268     thread, this call will block the calling thread until the mutex is
1269     unlocked.
1271   • pthread_mutex_trylock() will attempt to lock a mutex. However, if the mutex
1272     is already locked, the routine will return immediately with a "busy" error
1273     code. This routine may be useful in preventing deadlock conditions, as in a
1274     priority-inversion situation.
1276   • pthread_mutex_unlock() will unlock a mutex if called by the owning thread.
1277     Calling this routine is required after a thread has completed its use of
1278     protected data if other threads are to acquire the mutex for their work
1279     with the protected data. An error will be returned if:
1280       □ If the mutex was already unlocked
1281       □ If the mutex is owned by another thread
1283   • There is nothing "magical" about mutexes...in fact they are akin to a
1284     "gentlemen's agreement" between participating threads. It is up to the code
1285     writer to insure that the necessary threads all make the the mutex lock and
1286     unlock calls correctly. The following scenario demonstrates a logical
1287     error:
1289         Thread 1     Thread 2     Thread 3
1290         Lock         Lock
1291         A = 2        A = A+1      A = A*B
1292         Unlock       Unlock
1294    ● Question: When more than one thread is waiting for a locked mutex, which
1295      thread will be granted the lock first after it is released?
1296      [Answer]
1298 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1300 Example: Using Mutexes
1302     ┌───────────────────────────────────────────────────────────────────────────┐
1303     │ ● Example Code - Using Mutexes                                            │
1304     │                                                                           │
1305     │     This example program illustrates the use of mutex variables in a      │
1306     │     threads program that performs a dot product. The main data is made    │
1307     │     available to all threads through a globally accessible structure.     │
1308     │     Each thread works on a different part of the data. The main thread    │
1309     │     waits for all the threads to complete their computations, and then it │
1310     │     prints the resulting sum.                                             │
1311     │                                                                           │
1312     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
1313     │                                                                           │
1314     │ #include <pthread.h>                                                      │
1315     │ #include <stdio.h>                                                        │
1316     │ #include <stdlib.h>                                                       │
1317     │                                                                           │
1318     │ /*                                                                        │
1319     │ The following structure contains the necessary information                │
1320     │ to allow the function "dotprod" to access its input data and              │
1321     │ place its output into the structure.                                      │
1322     │ */                                                                        │
1323     │                                                                           │
1324     │ typedef struct                                                            │
1325     │  {                                                                        │
1326     │    double      *a;                                                        │
1327     │    double      *b;                                                        │
1328     │    double     sum;                                                        │
1329     │    int     veclen;                                                        │
1330     │  } DOTDATA;                                                               │
1331     │                                                                           │
1332     │ /* Define globally accessible variables and a mutex */                    │
1333     │                                                                           │
1334     │ #define NUMTHRDS 4                                                        │
1335     │ #define VECLEN 100                                                        │
1336     │    DOTDATA dotstr;                                                        │
1337     │    pthread_t callThd[NUMTHRDS];                                           │
1338     │    pthread_mutex_t mutexsum;                                              │
1339     │                                                                           │
1340     │ /*                                                                        │
1341     │ The function dotprod is activated when the thread is created.             │
1342     │ All input to this routine is obtained from a structure                    │
1343     │ of type DOTDATA and all output from this function is written into         │
1344     │ this structure. The benefit of this approach is apparent for the          │
1345     │ multi-threaded program: when a thread is created we pass a single         │
1346     │ argument to the activated function - typically this argument              │
1347     │ is a thread number. All  the other information required by the            │
1348     │ function is accessed from the globally accessible structure.              │
1349     │ */                                                                        │
1350     │                                                                           │
1351     │ void *dotprod(void *arg)                                                  │
1352     │ {                                                                         │
1353     │                                                                           │
1354     │    /* Define and use local variables for convenience */                   │
1355     │                                                                           │
1356     │    int i, start, end, len ;                                               │
1357     │    long offset;                                                           │
1358     │    double mysum, *x, *y;                                                  │
1359     │    offset = (long)arg;                                                    │
1360     │                                                                           │
1361     │    len = dotstr.veclen;                                                   │
1362     │    start = offset*len;                                                    │
1363     │    end   = start + len;                                                   │
1364     │    x = dotstr.a;                                                          │
1365     │    y = dotstr.b;                                                          │
1366     │                                                                           │
1367     │    /*                                                                     │
1368     │    Perform the dot product and assign result                              │
1369     │    to the appropriate variable in the structure.                          │
1370     │    */                                                                     │
1371     │                                                                           │
1372     │    mysum = 0;                                                             │
1373     │    for (i=start; i<end ; i++)                                             │
1374     │     {                                                                     │
1375     │       mysum += (x[i] * y[i]);                                             │
1376     │     }                                                                     │
1377     │                                                                           │
1378     │    /*                                                                     │
1379     │    Lock a mutex prior to updating the value in the shared                 │
1380     │    structure, and unlock it upon updating.                                │
1381     │    */                                                                     │
1382     │    pthread_mutex_lock (&mutexsum);                                        │
1383     │    dotstr.sum += mysum;                                                   │
1384     │    pthread_mutex_unlock (&mutexsum);                                      │
1385     │                                                                           │
1386     │    pthread_exit((void*) 0);                                               │
1387     │ }                                                                         │
1388     │                                                                           │
1389     │ /*                                                                        │
1390     │ The main program creates threads which do all the work and then           │
1391     │ print out result upon completion. Before creating the threads,            │
1392     │ the input data is created. Since all threads update a shared structure,   │
1393     │ we need a mutex for mutual exclusion. The main thread needs to wait for   │
1394     │ all threads to complete, it waits for each one of the threads. We specify │
1395     │ a thread attribute value that allow the main thread to join with the      │
1396     │ threads it creates. Note also that we free up handles when they are       │
1397     │ no longer needed.                                                         │
1398     │ */                                                                        │
1399     │                                                                           │
1400     │ int main (int argc, char *argv[])                                         │
1401     │ {                                                                         │
1402     │    long i;                                                                │
1403     │    double *a, *b;                                                         │
1404     │    void *status;                                                          │
1405     │    pthread_attr_t attr;                                                   │
1406     │                                                                           │
1407     │    /* Assign storage and initialize values */                             │
1408     │    a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double));                 │
1409     │    b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double));                 │
1410     │                                                                           │
1411     │    for (i=0; i<VECLEN*NUMTHRDS; i++)                                      │
1412     │     {                                                                     │
1413     │      a[i]=1.0;                                                            │
1414     │      b[i]=a[i];                                                           │
1415     │     }                                                                     │
1416     │                                                                           │
1417     │    dotstr.veclen = VECLEN;                                                │
1418     │    dotstr.a = a;                                                          │
1419     │    dotstr.b = b;                                                          │
1420     │    dotstr.sum=0;                                                          │
1421     │                                                                           │
1422     │    pthread_mutex_init(&mutexsum, NULL);                                   │
1423     │                                                                           │
1424     │    /* Create threads to perform the dotproduct  */                        │
1425     │    pthread_attr_init(&attr);                                              │
1426     │    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);           │
1427     │                                                                           │
1428     │         for(i=0; i<NUMTHRDS; i++)                                         │
1429     │         {                                                                 │
1430     │         /*                                                                │
1431     │         Each thread works on a different set of data.                     │
1432     │         The offset is specified by 'i'. The size of                       │
1433     │         the data for each thread is indicated by VECLEN.                  │
1434     │         */                                                                │
1435     │         pthread_create(&callThd[i], &attr, dotprod, (void *)i);           │
1436     │         }                                                                 │
1437     │                                                                           │
1438     │         pthread_attr_destroy(&attr);                                      │
1439     │                                                                           │
1440     │         /* Wait on the other threads */                                   │
1441     │         for(i=0; i<NUMTHRDS; i++)                                         │
1442     │         {                                                                 │
1443     │           pthread_join(callThd[i], &status);                              │
1444     │         }                                                                 │
1445     │                                                                           │
1446     │    /* After joining, print out the results and cleanup */                 │
1447     │    printf ("Sum =  %f \n", dotstr.sum);                                   │
1448     │    free (a);                                                              │
1449     │    free (b);                                                              │
1450     │    pthread_mutex_destroy(&mutexsum);                                      │
1451     │    pthread_exit(NULL);                                                    │
1452     │ }                                                                         │
1453     │                                                                           │
1454     │ View source code Serial version                                           │
1455     │ View source code Pthreads version                                         │
1456     └───────────────────────────────────────────────────────────────────────────┘
1460 ┌─────────────────────────────────────────────────────────────────────────────┐
1461 │ Condition Variables                                                         │
1462 └─────────────────────────────────────────────────────────────────────────────┘
1464 Overview
1466   • Condition variables provide yet another way for threads to synchronize.
1467     While mutexes implement synchronization by controlling thread access to
1468     data, condition variables allow threads to synchronize based upon the
1469     actual value of data.
1471   • Without condition variables, the programmer would need to have threads
1472     continually polling (possibly in a critical section), to check if the
1473     condition is met. This can be very resource consuming since the thread
1474     would be continuously busy in this activity. A condition variable is a way
1475     to achieve the same goal without polling.
1477   • A condition variable is always used in conjunction with a mutex lock.
1479   • A representative sequence for using condition variables is shown below.
1481     ┌─────────────────────────────────────────────────────────────────┐
1482     │ Main Thread                                                     │
1483     │                                                                 │
1484     │   • Declare and initialize global data/variables which require  │
1485     │     synchronization (such as "count")                           │
1486     │   • Declare and initialize a condition variable object          │
1487     │   • Declare and initialize an associated mutex                  │
1488     │   • Create threads A and B to do work                           │
1489     ├────────────────────────────────┬────────────────────────────────┤
1490     │ Thread A                       │ Thread B                       │
1491     │                                │                                │
1492     │   • Do work up to the point    │   • Do work                    │
1493     │     where a certain condition  │   • Lock associated mutex      │
1494     │     must occur (such as        │   • Change the value of the    │
1495     │     "count" must reach a       │     global variable that       │
1496     │     specified value)           │     Thread-A is waiting upon.  │
1497     │   • Lock associated mutex and  │   • Check value of the global  │
1498     │     check value of a global    │     Thread-A wait variable. If │
1499     │     variable                   │     it fulfills the desired    │
1500     │   • Call pthread_cond_wait()   │     condition, signal          │
1501     │     to perform a blocking wait │     Thread-A.                  │
1502     │     for signal from Thread-B.  │   • Unlock mutex.              │
1503     │     Note that a call to        │   • Continue                   │
1504     │     pthread_cond_wait()        │                                │
1505     │     automatically and          │                                │
1506     │     atomically unlocks the     │                                │
1507     │     associated mutex variable  │                                │
1508     │     so that it can be used by  │                                │
1509     │     Thread-B.                  │                                │
1510     │   • When signalled, wake up.   │                                │
1511     │     Mutex is automatically and │                                │
1512     │     atomically locked.         │                                │
1513     │   • Explicitly unlock mutex    │                                │
1514     │   • Continue                   │                                │
1515     ├────────────────────────────────┴────────────────────────────────┤
1516     │ Main Thread                                                     │
1517     │                                                                 │
1518     │     Join / Continue                                             │
1519     └─────────────────────────────────────────────────────────────────┘
1523 ┌─────────────────────────────────────────────────────────────────────────────┐
1524 │ Condition Variables                                                         │
1525 └─────────────────────────────────────────────────────────────────────────────┘
1527 Creating and Destroying Condition Variables
1529 [arrowBulle] Routines:
1532     ┌─────────────────────────────────────────────────────────────────┐
1533     │ pthread_cond_init (condition,attr)                              │
1534     │                                                                 │
1535     │ pthread_cond_destroy (condition)                                │
1536     │                                                                 │
1537     │ pthread_condattr_init (attr)                                    │
1538     │                                                                 │
1539     │ pthread_condattr_destroy (attr)                                 │
1540     └─────────────────────────────────────────────────────────────────┘
1542 [arrowBulle] Usage:
1545   • Condition variables must be declared with type pthread_cond_t, and must be
1546     initialized before they can be used. There are two ways to initialize a
1547     condition variable:
1549      1. Statically, when it is declared. For example:
1550         pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;
1552      2. Dynamically, with the pthread_cond_init() routine. The ID of the
1553         created condition variable is returned to the calling thread through
1554         the condition parameter. This method permits setting condition variable
1555         object attributes, attr.
1557   • The optional attr object is used to set condition variable attributes.
1558     There is only one attribute defined for condition variables:
1559     process-shared, which allows the condition variable to be seen by threads
1560     in other processes. The attribute object, if used, must be of type
1561     pthread_condattr_t (may be specified as NULL to accept defaults).
1563     Note that not all implementations may provide the process-shared attribute.
1565   • The pthread_condattr_init() and pthread_condattr_destroy() routines are
1566     used to create and destroy condition variable attribute objects.
1568   • pthread_cond_destroy() should be used to free a condition variable that is
1569     no longer needed.
1573 ┌─────────────────────────────────────────────────────────────────────────────┐
1574 │ Condition Variables                                                         │
1575 └─────────────────────────────────────────────────────────────────────────────┘
1577 Waiting and Signaling on Condition Variables
1579 [arrowBulle] Routines:
1582     ┌─────────────────────────────────────────────────────────────────┐
1583     │ pthread_cond_wait (condition,mutex)                             │
1584     │                                                                 │
1585     │ pthread_cond_signal (condition)                                 │
1586     │                                                                 │
1587     │ pthread_cond_broadcast (condition)                              │
1588     └─────────────────────────────────────────────────────────────────┘
1590 [arrowBulle] Usage:
1593   • pthread_cond_wait() blocks the calling thread until the specified condition
1594     is signalled. This routine should be called while mutex is locked, and it
1595     will automatically release the mutex while it waits. After signal is
1596     received and thread is awakened, mutex will be automatically locked for use
1597     by the thread. The programmer is then responsible for unlocking mutex when
1598     the thread is finished with it.
1600   • The pthread_cond_signal() routine is used to signal (or wake up) another
1601     thread which is waiting on the condition variable. It should be called
1602     after mutex is locked, and must unlock mutex in order for pthread_cond_wait
1603     () routine to complete.
1605   • The pthread_cond_broadcast() routine should be used instead of
1606     pthread_cond_signal() if more than one thread is in a blocking wait state.
1608   • It is a logical error to call pthread_cond_signal() before calling
1609     pthread_cond_wait().
1611 [warning5] Proper locking and unlocking of the associated mutex variable is
1612            essential when using these routines. For example:
1614              • Failing to lock the mutex before calling pthread_cond_wait() may
1615                cause it NOT to block.
1617              • Failing to unlock the mutex after calling pthread_cond_signal()
1618                may not allow a matching pthread_cond_wait() routine to complete
1619                (it will remain blocked).
1622 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1624 Example: Using Condition Variables
1626     ┌──────────────────────────────────────────────────────────────────────────────┐
1627     │ ● Example Code - Using Condition Variables                                   │
1628     │                                                                              │
1629     │     This simple example code demonstrates the use of several Pthread         │
1630     │     condition variable routines. The main routine creates three threads. Two │
1631     │     of the threads perform work and update a "count" variable. The third     │
1632     │     thread waits until the count variable reaches a specified value.         │
1633     │                                                                              │
1634     │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
1635     │                                                                              │
1636     │ #include <pthread.h>                                                         │
1637     │ #include <stdio.h>                                                           │
1638     │ #include <stdlib.h>                                                          │
1639     │                                                                              │
1640     │ #define NUM_THREADS  3                                                       │
1641     │ #define TCOUNT 10                                                            │
1642     │ #define COUNT_LIMIT 12                                                       │
1643     │                                                                              │
1644     │ int     count = 0;                                                           │
1645     │ int     thread_ids[3] = {0,1,2};                                             │
1646     │ pthread_mutex_t count_mutex;                                                 │
1647     │ pthread_cond_t count_threshold_cv;                                           │
1648     │                                                                              │
1649     │ void *inc_count(void *t)                                                     │
1650     │ {                                                                            │
1651     │   int i;                                                                     │
1652     │   long my_id = (long)t;                                                      │
1653     │                                                                              │
1654     │   for (i=0; i<TCOUNT; i++) {                                                 │
1655     │     pthread_mutex_lock(&count_mutex);                                        │
1656     │     count++;                                                                 │
1657     │                                                                              │
1658     │     /*                                                                       │
1659     │     Check the value of count and signal waiting thread when condition is     │
1660     │     reached.  Note that this occurs while mutex is locked.                   │
1661     │     */                                                                       │
1662     │     if (count == COUNT_LIMIT) {                                              │
1663     │       pthread_cond_signal(&count_threshold_cv);                              │
1664     │       printf("inc_count(): thread %ld, count = %d  Threshold reached.\n",    │
1665     │              my_id, count);                                                  │
1666     │       }                                                                      │
1667     │     printf("inc_count(): thread %ld, count = %d, unlocking mutex\n",         │
1668     │            my_id, count);                                                    │
1669     │     pthread_mutex_unlock(&count_mutex);                                      │
1670     │                                                                              │
1671     │     /* Do some "work" so threads can alternate on mutex lock */              │
1672     │     sleep(1);                                                                │
1673     │     }                                                                        │
1674     │   pthread_exit(NULL);                                                        │
1675     │ }                                                                            │
1676     │                                                                              │
1677     │ void *watch_count(void *t)                                                   │
1678     │ {                                                                            │
1679     │   long my_id = (long)t;                                                      │
1680     │                                                                              │
1681     │   printf("Starting watch_count(): thread %ld\n", my_id);                     │
1682     │                                                                              │
1683     │   /*                                                                         │
1684     │   Lock mutex and wait for signal.  Note that the pthread_cond_wait           │
1685     │   routine will automatically and atomically unlock mutex while it waits.     │
1686     │   Also, note that if COUNT_LIMIT is reached before this routine is run by    │
1687     │   the waiting thread, the loop will be skipped to prevent pthread_cond_wait  │
1688     │   from never returning.                                                      │
1689     │   */                                                                         │
1690     │   pthread_mutex_lock(&count_mutex);                                          │
1691     │   while (count<COUNT_LIMIT) {                                                │
1692     │     pthread_cond_wait(&count_threshold_cv, &count_mutex);                    │
1693     │     printf("watch_count(): thread %ld Condition signal received.\n", my_id); │
1694     │     count += 125;                                                            │
1695     │     printf("watch_count(): thread %ld count now = %d.\n", my_id, count);     │
1696     │     }                                                                        │
1697     │   pthread_mutex_unlock(&count_mutex);                                        │
1698     │   pthread_exit(NULL);                                                        │
1699     │ }                                                                            │
1700     │                                                                              │
1701     │ int main (int argc, char *argv[])                                            │
1702     │ {                                                                            │
1703     │   int i, rc;                                                                 │
1704     │   long t1=1, t2=2, t3=3;                                                     │
1705     │   pthread_t threads[3];                                                      │
1706     │   pthread_attr_t attr;                                                       │
1707     │                                                                              │
1708     │   /* Initialize mutex and condition variable objects */                      │
1709     │   pthread_mutex_init(&count_mutex, NULL);                                    │
1710     │   pthread_cond_init (&count_threshold_cv, NULL);                             │
1711     │                                                                              │
1712     │   /* For portability, explicitly create threads in a joinable state */       │
1713     │   pthread_attr_init(&attr);                                                  │
1714     │   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);               │
1715     │   pthread_create(&threads[0], &attr, watch_count, (void *)t1);               │
1716     │   pthread_create(&threads[1], &attr, inc_count, (void *)t2);                 │
1717     │   pthread_create(&threads[2], &attr, inc_count, (void *)t3);                 │
1718     │                                                                              │
1719     │   /* Wait for all threads to complete */                                     │
1720     │   for (i=0; i<NUM_THREADS; i++) {                                            │
1721     │     pthread_join(threads[i], NULL);                                          │
1722     │   }                                                                          │
1723     │   printf ("Main(): Waited on %d  threads. Done.\n", NUM_THREADS);            │
1724     │                                                                              │
1725     │   /* Clean up and exit */                                                    │
1726     │   pthread_attr_destroy(&attr);                                               │
1727     │   pthread_mutex_destroy(&count_mutex);                                       │
1728     │   pthread_cond_destroy(&count_threshold_cv);                                 │
1729     │   pthread_exit(NULL);                                                        │
1730     │                                                                              │
1731     │ }                                                                            │
1732     │                                                                              │
1733     │ View source code View sample output                                          │
1734     └──────────────────────────────────────────────────────────────────────────────┘
1738 ┌─────────────────────────────────────────────────────────────────────────────┐
1739 │ LLNL Specific Information and Recommendations                               │
1740 └─────────────────────────────────────────────────────────────────────────────┘
1743 This section describes details specific to Livermore Computing's systems.
1745 [arrowBulle] Implementations:
1748   • All LC production systems include a Pthreads implementation that follows
1749     draft 10 (final) of the POSIX standard. This is the preferred
1750     implementation.
1752   • Implementations differ in the maximum number of threads that a process may
1753     create. They also differ in the default amount of thread stack space.
1755 [arrowBulle] Compiling:
1758   • LC maintains a number of compilers, and usually several different versions
1759     of each - see the LC's Supported Compilers web page.
1761   • The compiler commands described in the Compiling Threaded Programs section
1762     apply to LC systems.
1764 [arrowBulle] Mixing MPI with Pthreads:
1767   • This is the primary motivation for using Pthreads at LC.
1769   • Design:
1770       □ Each MPI process typically creates and then manages N threads, where N
1771         makes the best use of the available CPUs/node.
1772       □ Finding the best value for N will vary with the platform and your
1773         application's characteristics.
1774       □ For IBM SP systems with two communication adapters per node, it may
1775         prove more efficient to use two (or more) MPI tasks per node.
1776       □ In general, there may be problems if multiple threads make MPI calls.
1777         The program may fail or behave unexpectedly. If MPI calls must be made
1778         from within a thread, they should be made only by one thread.
1780   • Compiling:
1781       □ Use the appropriate MPI compile command for the platform and language
1782         of choice
1783       □ Be sure to include the required Pthreads flag as shown in the Compiling
1784         Threaded Programs section.
1786   • An example code that uses both MPI and Pthreads is available below. The
1787     serial, threads-only, MPI-only and MPI-with-threads versions demonstrate
1788     one possible progression.
1789       □ Serial
1790       □ Pthreads only
1791       □ MPI only
1792       □ MPI with pthreads
1793       □ makefile (for IBM SP)
1795 [arrowBulle] Monitoring and Debugging Threads:
1798   • Debuggers vary in their ability to handle threads. The TotalView debugger
1799     is LC's recommended debugger for parallel programs, and is well suited for
1800     debugging threaded programs. See the TotalView Debugger tutorial for
1801     details.
1803   • The Linux ps command provides several flags for viewing thread information.
1804     Some examples are shown below. See the man page for details.
1806     ┌──────────────────────────────────────────────────────────────────┐
1807     │ % ps -Lf                                                         │
1808     │ UID        PID  PPID   LWP  C NLWP STIME TTY          TIME CMD   │
1809     │ blaise   22529 28240 22529  0    5 11:31 pts/53   00:00:00 a.out │
1810     │ blaise   22529 28240 22530 99    5 11:31 pts/53   00:01:24 a.out │
1811     │ blaise   22529 28240 22531 99    5 11:31 pts/53   00:01:24 a.out │
1812     │ blaise   22529 28240 22532 99    5 11:31 pts/53   00:01:24 a.out │
1813     │ blaise   22529 28240 22533 99    5 11:31 pts/53   00:01:24 a.out │
1814     │                                                                  │
1815     │ % ps -T                                                          │
1816     │   PID  SPID TTY          TIME CMD                                │
1817     │ 22529 22529 pts/53   00:00:00 a.out                              │
1818     │ 22529 22530 pts/53   00:01:49 a.out                              │
1819     │ 22529 22531 pts/53   00:01:49 a.out                              │
1820     │ 22529 22532 pts/53   00:01:49 a.out                              │
1821     │ 22529 22533 pts/53   00:01:49 a.out                              │
1822     │                                                                  │
1823     │ % ps -Lm                                                         │
1824     │   PID   LWP TTY          TIME CMD                                │
1825     │ 22529     - pts/53   00:18:56 a.out                              │
1826     │     - 22529 -        00:00:00 -                                  │
1827     │     - 22530 -        00:04:44 -                                  │
1828     │     - 22531 -        00:04:44 -                                  │
1829     │     - 22532 -        00:04:44 -                                  │
1830     │     - 22533 -        00:04:44 -                                  │
1831     └──────────────────────────────────────────────────────────────────┘
1833   • LC's Linux clusters also provide the top command to monitor processes on a
1834     node. If used with the -H flag, the threads contained within a process will
1835     be visible. An example of the top -H command is shown below. The parent
1836     process is PID 18010 which spawned three threads, shown as PIDs 18012,
1837     18013 and 18014.
1839     top -H command
1843 ┌─────────────────────────────────────────────────────────────────────────────┐
1844 │ Topics Not Covered                                                          │
1845 └─────────────────────────────────────────────────────────────────────────────┘
1848 Several features of the Pthreads API are not covered in this tutorial. These
1849 are listed below. See the Pthread Library Routines Reference section for more
1850 information.
1852   • Thread Scheduling
1853       □ Implementations will differ on how threads are scheduled to run. In
1854         most cases, the default mechanism is adequate.
1855       □ The Pthreads API provides routines to explicitly set thread scheduling
1856         policies and priorities which may override the default mechanisms.
1857       □ The API does not require implementations to support these features.
1859   • Keys: Thread-Specific Data
1860       □ As threads call and return from different routines, the local data on a
1861         thread's stack comes and goes.
1862       □ To preserve stack data you can usually pass it as an argument from one
1863         routine to the next, or else store the data in a global variable
1864         associated with a thread.
1865       □ Pthreads provides another, possibly more convenient and versatile, way
1866         of accomplishing this through keys.
1868   • Mutex Protocol Attributes and Mutex Priority Management for the handling of
1869     "priority inversion" problems.
1871   • Condition Variable Sharing - across processes
1873   • Thread Cancellation
1875   • Threads and Signals
1877   • Synchronization constructs - barriers and locks
1881 ┌─────────────────────────────────────────────────────────────────────────────┐
1882 │ Pthread Library Routines Reference                                          │
1883 └─────────────────────────────────────────────────────────────────────────────┘
1886     For convenience, an alphabetical list of Pthread routines, linked to their
1887     corresponding man page, is provided below.
1889     pthread_atfork
1890     pthread_attr_destroy
1891     pthread_attr_getdetachstate
1892     pthread_attr_getguardsize
1893     pthread_attr_getinheritsched
1894     pthread_attr_getschedparam
1895     pthread_attr_getschedpolicy
1896     pthread_attr_getscope
1897     pthread_attr_getstack
1898     pthread_attr_getstackaddr
1899     pthread_attr_getstacksize
1900     pthread_attr_init
1901     pthread_attr_setdetachstate
1902     pthread_attr_setguardsize
1903     pthread_attr_setinheritsched
1904     pthread_attr_setschedparam
1905     pthread_attr_setschedpolicy
1906     pthread_attr_setscope
1907     pthread_attr_setstack
1908     pthread_attr_setstackaddr
1909     pthread_attr_setstacksize
1910     pthread_barrier_destroy
1911     pthread_barrier_init
1912     pthread_barrier_wait
1913     pthread_barrierattr_destroy
1914     pthread_barrierattr_getpshared
1915     pthread_barrierattr_init
1916     pthread_barrierattr_setpshared
1917     pthread_cancel
1918     pthread_cleanup_pop
1919     pthread_cleanup_push
1920     pthread_cond_broadcast
1921     pthread_cond_destroy
1922     pthread_cond_init
1923     pthread_cond_signal
1924     pthread_cond_timedwait
1925     pthread_cond_wait
1926     pthread_condattr_destroy
1927     pthread_condattr_getclock
1928     pthread_condattr_getpshared
1929     pthread_condattr_init
1930     pthread_condattr_setclock
1931     pthread_condattr_setpshared
1932     pthread_create
1933     pthread_detach
1934     pthread_equal
1935     pthread_exit
1936     pthread_getconcurrency
1937     pthread_getcpuclockid
1938     pthread_getschedparam
1939     pthread_getspecific
1940     pthread_join
1941     pthread_key_create
1942     pthread_key_delete
1943     pthread_kill
1944     pthread_mutex_destroy
1945     pthread_mutex_getprioceiling
1946     pthread_mutex_init
1947     pthread_mutex_lock
1948     pthread_mutex_setprioceiling
1949     pthread_mutex_timedlock
1950     pthread_mutex_trylock
1951     pthread_mutex_unlock
1952     pthread_mutexattr_destroy
1953     pthread_mutexattr_getprioceiling
1954     pthread_mutexattr_getprotocol
1955     pthread_mutexattr_getpshared
1956     pthread_mutexattr_gettype
1957     pthread_mutexattr_init
1958     pthread_mutexattr_setprioceiling
1959     pthread_mutexattr_setprotocol
1960     pthread_mutexattr_setpshared
1961     pthread_mutexattr_settype
1962     pthread_once
1963     pthread_rwlock_destroy
1964     pthread_rwlock_init
1965     pthread_rwlock_rdlock
1966     pthread_rwlock_timedrdlock
1967     pthread_rwlock_timedwrlock
1968     pthread_rwlock_tryrdlock
1969     pthread_rwlock_trywrlock
1970     pthread_rwlock_unlock
1971     pthread_rwlock_wrlock
1972     pthread_rwlockattr_destroy
1973     pthread_rwlockattr_getpshared
1974     pthread_rwlockattr_init
1975     pthread_rwlockattr_setpshared
1976     pthread_self
1977     pthread_setcancelstate
1978     pthread_setcanceltype
1979     pthread_setconcurrency
1980     pthread_setschedparam
1981     pthread_setschedprio
1982     pthread_setspecific
1983     pthread_sigmask
1984     pthread_spin_destroy
1985     pthread_spin_init
1986     pthread_spin_lock
1987     pthread_spin_trylock
1988     pthread_spin_unlock
1989     pthread_testcancel
1991 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1993 This completes the tutorial.
1995 Evaluation  Please complete the online evaluation form - unless you are doing
1996 Form        the exercise, in which case please complete it at the end of the
1997             exercise.
1999 Where would you like to go now?
2001   • Exercise
2002   • Agenda
2003   • Back to the top
2007 ┌─────────────────────────────────────────────────────────────────────────────┐
2008 │ References and More Information                                             │
2009 └─────────────────────────────────────────────────────────────────────────────┘
2012   • Author: Blaise Barney, Livermore Computing.
2014   • POSIX Standard: www.unix.org/version3/ieee_std.html
2016   • "Pthreads Programming". B. Nichols et al. O'Reilly and Associates.
2018   • "Threads Primer". B. Lewis and D. Berg. Prentice Hall
2020   • "Programming With POSIX Threads". D. Butenhof. Addison Wesley
2021     www.awl.com/cseng/titles/0-201-63392-2
2023   • "Programming With Threads". S. Kleiman et al. Prentice Hall