(CFLAGS-tst-align.c): Add -mpreferred-stack-boundary=4.
[glibc.git] / linuxthreads / linuxthreads.texi
blob795fb70977dd9e97b5ab525d31b2985b7a4ef1bf
1 @node POSIX Threads
2 @c @node POSIX Threads, , Top, Top
3 @chapter POSIX Threads
4 @c %MENU% The standard threads library
6 @c This chapter needs more work bigtime. -zw
8 This chapter describes the pthreads (POSIX threads) library.  This
9 library provides support functions for multithreaded programs: thread
10 primitives, synchronization objects, and so forth.  It also implements
11 POSIX 1003.1b semaphores (not to be confused with System V semaphores).
13 The threads operations (@samp{pthread_*}) do not use @var{errno}.
14 Instead they return an error code directly.  The semaphore operations do
15 use @var{errno}.
17 @menu
18 * Basic Thread Operations::     Creating, terminating, and waiting for threads.
19 * Thread Attributes::           Tuning thread scheduling.
20 * Cancellation::                Stopping a thread before it's done.
21 * Cleanup Handlers::            Deallocating resources when a thread is
22                                   canceled.
23 * Mutexes::                     One way to synchronize threads.
24 * Condition Variables::         Another way.
25 * POSIX Semaphores::            And a third way.
26 * Thread-Specific Data::        Variables with different values in
27                                   different threads.
28 * Threads and Signal Handling:: Why you should avoid mixing the two, and
29                                   how to do it if you must.
30 * Threads and Fork::            Interactions between threads and the
31                                   @code{fork} function.
32 * Streams and Fork::            Interactions between stdio streams and
33                                   @code{fork}.
34 * Miscellaneous Thread Functions:: A grab bag of utility routines.
35 @end menu
37 @node Basic Thread Operations
38 @section Basic Thread Operations
40 These functions are the thread equivalents of @code{fork}, @code{exit},
41 and @code{wait}.
43 @comment pthread.h
44 @comment POSIX
45 @deftypefun int pthread_create (pthread_t * @var{thread}, pthread_attr_t * @var{attr}, void * (*@var{start_routine})(void *), void * @var{arg})
46 @code{pthread_create} creates a new thread of control that executes
47 concurrently with the calling thread. The new thread calls the
48 function @var{start_routine}, passing it @var{arg} as first argument. The
49 new thread terminates either explicitly, by calling @code{pthread_exit},
50 or implicitly, by returning from the @var{start_routine} function. The
51 latter case is equivalent to calling @code{pthread_exit} with the result
52 returned by @var{start_routine} as exit code.
54 The @var{attr} argument specifies thread attributes to be applied to the
55 new thread. @xref{Thread Attributes}, for details. The @var{attr}
56 argument can also be @code{NULL}, in which case default attributes are
57 used: the created thread is joinable (not detached) and has an ordinary
58 (not realtime) scheduling policy.
60 On success, the identifier of the newly created thread is stored in the
61 location pointed by the @var{thread} argument, and a 0 is returned. On
62 error, a non-zero error code is returned.
64 This function may return the following errors:
65 @table @code
66 @item EAGAIN
67 Not enough system resources to create a process for the new thread,
68 or more than @code{PTHREAD_THREADS_MAX} threads are already active.
69 @end table
70 @end deftypefun
72 @comment pthread.h
73 @comment POSIX
74 @deftypefun void pthread_exit (void *@var{retval})
75 @code{pthread_exit} terminates the execution of the calling thread.  All
76 cleanup handlers (@pxref{Cleanup Handlers}) that have been set for the
77 calling thread with @code{pthread_cleanup_push} are executed in reverse
78 order (the most recently pushed handler is executed first). Finalization
79 functions for thread-specific data are then called for all keys that
80 have non-@code{NULL} values associated with them in the calling thread
81 (@pxref{Thread-Specific Data}).  Finally, execution of the calling
82 thread is stopped.
84 The @var{retval} argument is the return value of the thread. It can be
85 retrieved from another thread using @code{pthread_join}.
87 The @code{pthread_exit} function never returns.
88 @end deftypefun
90 @comment pthread.h
91 @comment POSIX
92 @deftypefun int pthread_cancel (pthread_t @var{thread})
94 @code{pthread_cancel} sends a cancellation request to the thread denoted
95 by the @var{thread} argument.  If there is no such thread,
96 @code{pthread_cancel} fails and returns @code{ESRCH}.  Otherwise it
97 returns 0. @xref{Cancellation}, for details.
98 @end deftypefun
100 @comment pthread.h
101 @comment POSIX
102 @deftypefun int pthread_join (pthread_t @var{th}, void **thread_@var{return})
103 @code{pthread_join} suspends the execution of the calling thread until
104 the thread identified by @var{th} terminates, either by calling
105 @code{pthread_exit} or by being canceled.
107 If @var{thread_return} is not @code{NULL}, the return value of @var{th}
108 is stored in the location pointed to by @var{thread_return}.  The return
109 value of @var{th} is either the argument it gave to @code{pthread_exit},
110 or @code{PTHREAD_CANCELED} if @var{th} was canceled.
112 The joined thread @code{th} must be in the joinable state: it must not
113 have been detached using @code{pthread_detach} or the
114 @code{PTHREAD_CREATE_DETACHED} attribute to @code{pthread_create}.
116 When a joinable thread terminates, its memory resources (thread
117 descriptor and stack) are not deallocated until another thread performs
118 @code{pthread_join} on it. Therefore, @code{pthread_join} must be called
119 once for each joinable thread created to avoid memory leaks.
121 At most one thread can wait for the termination of a given
122 thread. Calling @code{pthread_join} on a thread @var{th} on which
123 another thread is already waiting for termination returns an error.
125 @code{pthread_join} is a cancellation point. If a thread is canceled
126 while suspended in @code{pthread_join}, the thread execution resumes
127 immediately and the cancellation is executed without waiting for the
128 @var{th} thread to terminate. If cancellation occurs during
129 @code{pthread_join}, the @var{th} thread remains not joined.
131 On success, the return value of @var{th} is stored in the location
132 pointed to by @var{thread_return}, and 0 is returned. On error, one of
133 the following values is returned:
134 @table @code
135 @item ESRCH
136 No thread could be found corresponding to that specified by @var{th}.
137 @item EINVAL
138 The @var{th} thread has been detached, or another thread is already
139 waiting on termination of @var{th}.
140 @item EDEADLK
141 The @var{th} argument refers to the calling thread.
142 @end table
143 @end deftypefun
145 @node Thread Attributes
146 @section Thread Attributes
148 @comment pthread.h
149 @comment POSIX
151 Threads have a number of attributes that may be set at creation time.
152 This is done by filling a thread attribute object @var{attr} of type
153 @code{pthread_attr_t}, then passing it as second argument to
154 @code{pthread_create}. Passing @code{NULL} is equivalent to passing a
155 thread attribute object with all attributes set to their default values.
157 Attribute objects are consulted only when creating a new thread.  The
158 same attribute object can be used for creating several threads.
159 Modifying an attribute object after a call to @code{pthread_create} does
160 not change the attributes of the thread previously created.
162 @comment pthread.h
163 @comment POSIX
164 @deftypefun int pthread_attr_init (pthread_attr_t *@var{attr})
165 @code{pthread_attr_init} initializes the thread attribute object
166 @var{attr} and fills it with default values for the attributes. (The
167 default values are listed below for each attribute.)
169 Each attribute @var{attrname} (see below for a list of all attributes)
170 can be individually set using the function
171 @code{pthread_attr_set@var{attrname}} and retrieved using the function
172 @code{pthread_attr_get@var{attrname}}.
173 @end deftypefun
175 @comment pthread.h
176 @comment POSIX
177 @deftypefun int pthread_attr_destroy (pthread_attr_t *@var{attr})
178 @code{pthread_attr_destroy} destroys the attribute object pointed to by
179 @var{attr} releasing any resources associated with it.  @var{attr} is
180 left in an undefined state, and you must not use it again in a call to
181 any pthreads function until it has been reinitialized.
182 @end deftypefun
184 @findex pthread_attr_setdetachstate
185 @findex pthread_attr_setguardsize
186 @findex pthread_attr_setinheritsched
187 @findex pthread_attr_setschedparam
188 @findex pthread_attr_setschedpolicy
189 @findex pthread_attr_setscope
190 @findex pthread_attr_setstack
191 @findex pthread_attr_setstackaddr
192 @findex pthread_attr_setstacksize
193 @comment pthread.h
194 @comment POSIX
195 @deftypefun int pthread_attr_setattr (pthread_attr_t *@var{obj}, int @var{value})
196 Set attribute @var{attr} to @var{value} in the attribute object pointed
197 to by @var{obj}.  See below for a list of possible attributes and the
198 values they can take.
200 On success, these functions return 0.  If @var{value} is not meaningful
201 for the @var{attr} being modified, they will return the error code
202 @code{EINVAL}.  Some of the functions have other failure modes; see
203 below.
204 @end deftypefun
206 @findex pthread_attr_getdetachstate
207 @findex pthread_attr_getguardsize
208 @findex pthread_attr_getinheritsched
209 @findex pthread_attr_getschedparam
210 @findex pthread_attr_getschedpolicy
211 @findex pthread_attr_getscope
212 @findex pthread_attr_getstack
213 @findex pthread_attr_getstackaddr
214 @findex pthread_attr_getstacksize
215 @comment pthread.h
216 @comment POSIX
217 @deftypefun int pthread_attr_getattr (const pthread_attr_t *@var{obj}, int *@var{value})
218 Store the current setting of @var{attr} in @var{obj} into the variable
219 pointed to by @var{value}.
221 These functions always return 0.
222 @end deftypefun
224 The following thread attributes are supported:
225 @table @samp
226 @item detachstate
227 Choose whether the thread is created in the joinable state (value
228 @code{PTHREAD_CREATE_JOINABLE}) or in the detached state
229 (@code{PTHREAD_CREATE_DETACHED}).  The default is
230 @code{PTHREAD_CREATE_JOINABLE}.
232 In the joinable state, another thread can synchronize on the thread
233 termination and recover its termination code using @code{pthread_join},
234 but some of the thread resources are kept allocated after the thread
235 terminates, and reclaimed only when another thread performs
236 @code{pthread_join} on that thread.
238 In the detached state, the thread resources are immediately freed when
239 it terminates, but @code{pthread_join} cannot be used to synchronize on
240 the thread termination.
242 A thread created in the joinable state can later be put in the detached
243 thread using @code{pthread_detach}.
245 @item schedpolicy
246 Select the scheduling policy for the thread: one of @code{SCHED_OTHER}
247 (regular, non-realtime scheduling), @code{SCHED_RR} (realtime,
248 round-robin) or @code{SCHED_FIFO} (realtime, first-in first-out).
249 The default is @code{SCHED_OTHER}.
250 @c Not doc'd in our manual: FIXME.
251 @c See @code{sched_setpolicy} for more information on scheduling policies.
253 The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
254 are available only to processes with superuser privileges.
255 @code{pthread_attr_setschedparam} will fail and return @code{ENOTSUP} if
256 you try to set a realtime policy when you are unprivileged.
258 The scheduling policy of a thread can be changed after creation with
259 @code{pthread_setschedparam}.
261 @item schedparam
262 Change the scheduling parameter (the scheduling priority)
263 for the thread.  The default is 0.
265 This attribute is not significant if the scheduling policy is
266 @code{SCHED_OTHER}; it only matters for the realtime policies
267 @code{SCHED_RR} and @code{SCHED_FIFO}.
269 The scheduling priority of a thread can be changed after creation with
270 @code{pthread_setschedparam}.
272 @item inheritsched
273 Choose whether the scheduling policy and scheduling parameter for the
274 newly created thread are determined by the values of the
275 @var{schedpolicy} and @var{schedparam} attributes (value
276 @code{PTHREAD_EXPLICIT_SCHED}) or are inherited from the parent thread
277 (value @code{PTHREAD_INHERIT_SCHED}).  The default is
278 @code{PTHREAD_EXPLICIT_SCHED}.
280 @item scope
281 Choose the scheduling contention scope for the created thread.  The
282 default is @code{PTHREAD_SCOPE_SYSTEM}, meaning that the threads contend
283 for CPU time with all processes running on the machine. In particular,
284 thread priorities are interpreted relative to the priorities of all
285 other processes on the machine. The other possibility,
286 @code{PTHREAD_SCOPE_PROCESS}, means that scheduling contention occurs
287 only between the threads of the running process: thread priorities are
288 interpreted relative to the priorities of the other threads of the
289 process, regardless of the priorities of other processes.
291 @code{PTHREAD_SCOPE_PROCESS} is not supported in LinuxThreads.  If you
292 try to set the scope to this value, @code{pthread_attr_setscope} will
293 fail and return @code{ENOTSUP}.
295 @item stackaddr
296 Provide an address for an application managed stack.  The size of the
297 stack must be at least @code{PTHREAD_STACK_MIN}.
299 @item stacksize
300 Change the size of the stack created for the thread.  The value defines
301 the minimum stack size, in bytes.
303 If the value exceeds the system's maximum stack size, or is smaller
304 than @code{PTHREAD_STACK_MIN}, @code{pthread_attr_setstacksize} will
305 fail and return @code{EINVAL}.
307 @item stack
308 Provide both the address and size of an application managed stack to
309 use for the new thread.  The base of the memory area is @var{stackaddr}
310 with the size of the memory area, @var{stacksize}, measured in bytes.
312 If the value of @var{stacksize} is less than @code{PTHREAD_STACK_MIN},
313 or greater than the system's maximum stack size, or if the value of
314 @var{stackaddr} lacks the proper alignment, @code{pthread_attr_setstack}
315 will fail and return @code{EINVAL}.
317 @item guardsize
318 Change the minimum size in bytes of the guard area for the thread's
319 stack.  The default size is a single page.  If this value is set, it
320 will be rounded up to the nearest page size.  If the value is set to 0,
321 a guard area will not be created for this thread.  The space allocated
322 for the guard area is used to catch stack overflow.  Therefore, when
323 allocating large structures on the stack, a larger guard area may be
324 required to catch a stack overflow.
326 If the caller is managing their own stacks (if the @code{stackaddr}
327 attribute has been set), then the @code{guardsize} attribute is ignored.
329 If the value exceeds the @code{stacksize}, @code{pthread_atrr_setguardsize}
330 will fail and return @code{EINVAL}.
331 @end table
333 @node Cancellation
334 @section Cancellation
336 Cancellation is the mechanism by which a thread can terminate the
337 execution of another thread. More precisely, a thread can send a
338 cancellation request to another thread. Depending on its settings, the
339 target thread can then either ignore the request, honor it immediately,
340 or defer it till it reaches a cancellation point.  When threads are
341 first created by @code{pthread_create}, they always defer cancellation
342 requests.
344 When a thread eventually honors a cancellation request, it behaves as if
345 @code{pthread_exit(PTHREAD_CANCELED)} was called.  All cleanup handlers
346 are executed in reverse order, finalization functions for
347 thread-specific data are called, and finally the thread stops executing.
348 If the canceled thread was joinable, the return value
349 @code{PTHREAD_CANCELED} is provided to whichever thread calls
350 @var{pthread_join} on it. See @code{pthread_exit} for more information.
352 Cancellation points are the points where the thread checks for pending
353 cancellation requests and performs them.  The POSIX threads functions
354 @code{pthread_join}, @code{pthread_cond_wait},
355 @code{pthread_cond_timedwait}, @code{pthread_testcancel},
356 @code{sem_wait}, and @code{sigwait} are cancellation points.  In
357 addition, these system calls are cancellation points:
359 @multitable @columnfractions .33 .33 .33
360 @item @t{accept}        @tab @t{open}           @tab @t{sendmsg}
361 @item @t{close}         @tab @t{pause}          @tab @t{sendto}
362 @item @t{connect}       @tab @t{read}           @tab @t{system}
363 @item @t{fcntl}         @tab @t{recv}           @tab @t{tcdrain}
364 @item @t{fsync}         @tab @t{recvfrom}       @tab @t{wait}
365 @item @t{lseek}         @tab @t{recvmsg}        @tab @t{waitpid}
366 @item @t{msync}         @tab @t{send}           @tab @t{write}
367 @item @t{nanosleep}
368 @end multitable
370 @noindent
371 All library functions that call these functions (such as
372 @code{printf}) are also cancellation points.
374 @comment pthread.h
375 @comment POSIX
376 @deftypefun int pthread_setcancelstate (int @var{state}, int *@var{oldstate})
377 @code{pthread_setcancelstate} changes the cancellation state for the
378 calling thread -- that is, whether cancellation requests are ignored or
379 not. The @var{state} argument is the new cancellation state: either
380 @code{PTHREAD_CANCEL_ENABLE} to enable cancellation, or
381 @code{PTHREAD_CANCEL_DISABLE} to disable cancellation (cancellation
382 requests are ignored).
384 If @var{oldstate} is not @code{NULL}, the previous cancellation state is
385 stored in the location pointed to by @var{oldstate}, and can thus be
386 restored later by another call to @code{pthread_setcancelstate}.
388 If the @var{state} argument is not @code{PTHREAD_CANCEL_ENABLE} or
389 @code{PTHREAD_CANCEL_DISABLE}, @code{pthread_setcancelstate} fails and
390 returns @code{EINVAL}.  Otherwise it returns 0.
391 @end deftypefun
393 @comment pthread.h
394 @comment POSIX
395 @deftypefun int pthread_setcanceltype (int @var{type}, int *@var{oldtype})
396 @code{pthread_setcanceltype} changes the type of responses to
397 cancellation requests for the calling thread: asynchronous (immediate)
398 or deferred.  The @var{type} argument is the new cancellation type:
399 either @code{PTHREAD_CANCEL_ASYNCHRONOUS} to cancel the calling thread
400 as soon as the cancellation request is received, or
401 @code{PTHREAD_CANCEL_DEFERRED} to keep the cancellation request pending
402 until the next cancellation point. If @var{oldtype} is not @code{NULL},
403 the previous cancellation state is stored in the location pointed to by
404 @var{oldtype}, and can thus be restored later by another call to
405 @code{pthread_setcanceltype}.
407 If the @var{type} argument is not @code{PTHREAD_CANCEL_DEFERRED} or
408 @code{PTHREAD_CANCEL_ASYNCHRONOUS}, @code{pthread_setcanceltype} fails
409 and returns @code{EINVAL}.  Otherwise it returns 0.
410 @end deftypefun
412 @comment pthread.h
413 @comment POSIX
414 @deftypefun void pthread_testcancel (@var{void})
415 @code{pthread_testcancel} does nothing except testing for pending
416 cancellation and executing it. Its purpose is to introduce explicit
417 checks for cancellation in long sequences of code that do not call
418 cancellation point functions otherwise.
419 @end deftypefun
421 @node Cleanup Handlers
422 @section Cleanup Handlers
424 Cleanup handlers are functions that get called when a thread terminates,
425 either by calling @code{pthread_exit} or because of
426 cancellation. Cleanup handlers are installed and removed following a
427 stack-like discipline.
429 The purpose of cleanup handlers is to free the resources that a thread
430 may hold at the time it terminates. In particular, if a thread exits or
431 is canceled while it owns a locked mutex, the mutex will remain locked
432 forever and prevent other threads from executing normally. The best way
433 to avoid this is, just before locking the mutex, to install a cleanup
434 handler whose effect is to unlock the mutex. Cleanup handlers can be
435 used similarly to free blocks allocated with @code{malloc} or close file
436 descriptors on thread termination.
438 Here is how to lock a mutex @var{mut} in such a way that it will be
439 unlocked if the thread is canceled while @var{mut} is locked:
441 @smallexample
442 pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
443 pthread_mutex_lock(&mut);
444 /* do some work */
445 pthread_mutex_unlock(&mut);
446 pthread_cleanup_pop(0);
447 @end smallexample
449 Equivalently, the last two lines can be replaced by
451 @smallexample
452 pthread_cleanup_pop(1);
453 @end smallexample
455 Notice that the code above is safe only in deferred cancellation mode
456 (see @code{pthread_setcanceltype}). In asynchronous cancellation mode, a
457 cancellation can occur between @code{pthread_cleanup_push} and
458 @code{pthread_mutex_lock}, or between @code{pthread_mutex_unlock} and
459 @code{pthread_cleanup_pop}, resulting in both cases in the thread trying
460 to unlock a mutex not locked by the current thread. This is the main
461 reason why asynchronous cancellation is difficult to use.
463 If the code above must also work in asynchronous cancellation mode,
464 then it must switch to deferred mode for locking and unlocking the
465 mutex:
467 @smallexample
468 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
469 pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
470 pthread_mutex_lock(&mut);
471 /* do some work */
472 pthread_cleanup_pop(1);
473 pthread_setcanceltype(oldtype, NULL);
474 @end smallexample
476 The code above can be rewritten in a more compact and efficient way,
477 using the non-portable functions @code{pthread_cleanup_push_defer_np}
478 and @code{pthread_cleanup_pop_restore_np}:
480 @smallexample
481 pthread_cleanup_push_defer_np(pthread_mutex_unlock, (void *) &mut);
482 pthread_mutex_lock(&mut);
483 /* do some work */
484 pthread_cleanup_pop_restore_np(1);
485 @end smallexample
487 @comment pthread.h
488 @comment POSIX
489 @deftypefun void pthread_cleanup_push (void (*@var{routine}) (void *), void *@var{arg})
491 @code{pthread_cleanup_push} installs the @var{routine} function with
492 argument @var{arg} as a cleanup handler. From this point on to the
493 matching @code{pthread_cleanup_pop}, the function @var{routine} will be
494 called with arguments @var{arg} when the thread terminates, either
495 through @code{pthread_exit} or by cancellation. If several cleanup
496 handlers are active at that point, they are called in LIFO order: the
497 most recently installed handler is called first.
498 @end deftypefun
500 @comment pthread.h
501 @comment POSIX
502 @deftypefun void pthread_cleanup_pop (int @var{execute})
503 @code{pthread_cleanup_pop} removes the most recently installed cleanup
504 handler. If the @var{execute} argument is not 0, it also executes the
505 handler, by calling the @var{routine} function with arguments
506 @var{arg}. If the @var{execute} argument is 0, the handler is only
507 removed but not executed.
508 @end deftypefun
510 Matching pairs of @code{pthread_cleanup_push} and
511 @code{pthread_cleanup_pop} must occur in the same function, at the same
512 level of block nesting.  Actually, @code{pthread_cleanup_push} and
513 @code{pthread_cleanup_pop} are macros, and the expansion of
514 @code{pthread_cleanup_push} introduces an open brace @code{@{} with the
515 matching closing brace @code{@}} being introduced by the expansion of the
516 matching @code{pthread_cleanup_pop}.
518 @comment pthread.h
519 @comment GNU
520 @deftypefun void pthread_cleanup_push_defer_np (void (*@var{routine}) (void *), void *@var{arg})
521 @code{pthread_cleanup_push_defer_np} is a non-portable extension that
522 combines @code{pthread_cleanup_push} and @code{pthread_setcanceltype}.
523 It pushes a cleanup handler just as @code{pthread_cleanup_push} does,
524 but also saves the current cancellation type and sets it to deferred
525 cancellation. This ensures that the cleanup mechanism is effective even
526 if the thread was initially in asynchronous cancellation mode.
527 @end deftypefun
529 @comment pthread.h
530 @comment GNU
531 @deftypefun void pthread_cleanup_pop_restore_np (int @var{execute})
532 @code{pthread_cleanup_pop_restore_np} pops a cleanup handler introduced
533 by @code{pthread_cleanup_push_defer_np}, and restores the cancellation
534 type to its value at the time @code{pthread_cleanup_push_defer_np} was
535 called.
536 @end deftypefun
538 @code{pthread_cleanup_push_defer_np} and
539 @code{pthread_cleanup_pop_restore_np} must occur in matching pairs, at
540 the same level of block nesting.
542 The sequence
544 @smallexample
545 pthread_cleanup_push_defer_np(routine, arg);
547 pthread_cleanup_pop_restore_np(execute);
548 @end smallexample
550 @noindent
551 is functionally equivalent to (but more compact and efficient than)
553 @smallexample
555   int oldtype;
556   pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
557   pthread_cleanup_push(routine, arg);
558   ...
559   pthread_cleanup_pop(execute);
560   pthread_setcanceltype(oldtype, NULL);
562 @end smallexample
565 @node Mutexes
566 @section Mutexes
568 A mutex is a MUTual EXclusion device, and is useful for protecting
569 shared data structures from concurrent modifications, and implementing
570 critical sections and monitors.
572 A mutex has two possible states: unlocked (not owned by any thread),
573 and locked (owned by one thread). A mutex can never be owned by two
574 different threads simultaneously. A thread attempting to lock a mutex
575 that is already locked by another thread is suspended until the owning
576 thread unlocks the mutex first.
578 None of the mutex functions is a cancellation point, not even
579 @code{pthread_mutex_lock}, in spite of the fact that it can suspend a
580 thread for arbitrary durations. This way, the status of mutexes at
581 cancellation points is predictable, allowing cancellation handlers to
582 unlock precisely those mutexes that need to be unlocked before the
583 thread stops executing. Consequently, threads using deferred
584 cancellation should never hold a mutex for extended periods of time.
586 It is not safe to call mutex functions from a signal handler.  In
587 particular, calling @code{pthread_mutex_lock} or
588 @code{pthread_mutex_unlock} from a signal handler may deadlock the
589 calling thread.
591 @comment pthread.h
592 @comment POSIX
593 @deftypefun int pthread_mutex_init (pthread_mutex_t *@var{mutex}, const pthread_mutexattr_t *@var{mutexattr})
595 @code{pthread_mutex_init} initializes the mutex object pointed to by
596 @var{mutex} according to the mutex attributes specified in @var{mutexattr}.
597 If @var{mutexattr} is @code{NULL}, default attributes are used instead.
599 The LinuxThreads implementation supports only one mutex attribute,
600 the @var{mutex type}, which is either ``fast'', ``recursive'', or
601 ``error checking''. The type of a mutex determines whether
602 it can be locked again by a thread that already owns it.
603 The default type is ``fast''.
605 Variables of type @code{pthread_mutex_t} can also be initialized
606 statically, using the constants @code{PTHREAD_MUTEX_INITIALIZER} (for
607 timed mutexes), @code{PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP} (for
608 recursive mutexes), @code{PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP}
609 (for fast mutexes(, and @code{PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP}
610 (for error checking mutexes).
612 @code{pthread_mutex_init} always returns 0.
613 @end deftypefun
615 @comment pthread.h
616 @comment POSIX
617 @deftypefun int pthread_mutex_lock (pthread_mutex_t *mutex))
618 @code{pthread_mutex_lock} locks the given mutex. If the mutex is
619 currently unlocked, it becomes locked and owned by the calling thread,
620 and @code{pthread_mutex_lock} returns immediately. If the mutex is
621 already locked by another thread, @code{pthread_mutex_lock} suspends the
622 calling thread until the mutex is unlocked.
624 If the mutex is already locked by the calling thread, the behavior of
625 @code{pthread_mutex_lock} depends on the type of the mutex. If the mutex
626 is of the ``fast'' type, the calling thread is suspended.  It will
627 remain suspended forever, because no other thread can unlock the mutex.
628 If  the mutex is of the ``error checking'' type, @code{pthread_mutex_lock}
629 returns immediately with the error code @code{EDEADLK}.  If the mutex is
630 of the ``recursive'' type, @code{pthread_mutex_lock} succeeds and
631 returns immediately, recording the number of times the calling thread
632 has locked the mutex. An equal number of @code{pthread_mutex_unlock}
633 operations must be performed before the mutex returns to the unlocked
634 state.
635 @c This doesn't discuss PTHREAD_MUTEX_TIMED_NP mutex attributes. FIXME
636 @end deftypefun
638 @comment pthread.h
639 @comment POSIX
640 @deftypefun int pthread_mutex_trylock (pthread_mutex_t *@var{mutex})
641 @code{pthread_mutex_trylock} behaves identically to
642 @code{pthread_mutex_lock}, except that it does not block the calling
643 thread if the mutex is already locked by another thread (or by the
644 calling thread in the case of a ``fast'' mutex). Instead,
645 @code{pthread_mutex_trylock} returns immediately with the error code
646 @code{EBUSY}.
647 @end deftypefun
649 @comment pthread.h
650 @comment POSIX
651 @deftypefun int pthread_mutex_timedlock (pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime})
652 The @code{pthread_mutex_timedlock} is similar to the
653 @code{pthread_mutex_lock} function but instead of blocking for in
654 indefinite time if the mutex is locked by another thread, it returns
655 when the time specified in @var{abstime} is reached.
657 This function can only be used on standard (``timed'') and ``error
658 checking'' mutexes.  It behaves just like @code{pthread_mutex_lock} for
659 all other types.
661 If the mutex is successfully locked, the function returns zero.  If the
662 time specified in @var{abstime} is reached without the mutex being locked,
663 @code{ETIMEDOUT} is returned.
665 This function was introduced in the POSIX.1d revision of the POSIX standard.
666 @end deftypefun
668 @comment pthread.h
669 @comment POSIX
670 @deftypefun int pthread_mutex_unlock (pthread_mutex_t *@var{mutex})
671 @code{pthread_mutex_unlock} unlocks the given mutex. The mutex is
672 assumed to be locked and owned by the calling thread on entrance to
673 @code{pthread_mutex_unlock}. If the mutex is of the ``fast'' type,
674 @code{pthread_mutex_unlock} always returns it to the unlocked state. If
675 it is of the ``recursive'' type, it decrements the locking count of the
676 mutex (number of @code{pthread_mutex_lock} operations performed on it by
677 the calling thread), and only when this count reaches zero is the mutex
678 actually unlocked.
680 On ``error checking'' mutexes, @code{pthread_mutex_unlock} actually
681 checks at run-time that the mutex is locked on entrance, and that it was
682 locked by the same thread that is now calling
683 @code{pthread_mutex_unlock}.  If these conditions are not met,
684 @code{pthread_mutex_unlock} returns @code{EPERM}, and the mutex remains
685 unchanged.  ``Fast'' and ``recursive'' mutexes perform no such checks,
686 thus allowing a locked mutex to be unlocked by a thread other than its
687 owner. This is non-portable behavior and must not be relied upon.
688 @end deftypefun
690 @comment pthread.h
691 @comment POSIX
692 @deftypefun int pthread_mutex_destroy (pthread_mutex_t *@var{mutex})
693 @code{pthread_mutex_destroy} destroys a mutex object, freeing the
694 resources it might hold. The mutex must be unlocked on entrance. In the
695 LinuxThreads implementation, no resources are associated with mutex
696 objects, thus @code{pthread_mutex_destroy} actually does nothing except
697 checking that the mutex is unlocked.
699 If the mutex is locked by some thread, @code{pthread_mutex_destroy}
700 returns @code{EBUSY}.  Otherwise it returns 0.
701 @end deftypefun
703 If any of the above functions (except @code{pthread_mutex_init})
704 is applied to an uninitialized mutex, they will simply return
705 @code{EINVAL} and do nothing.
707 A shared global variable @var{x} can be protected by a mutex as follows:
709 @smallexample
710 int x;
711 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
712 @end smallexample
714 All accesses and modifications to @var{x} should be bracketed by calls to
715 @code{pthread_mutex_lock} and @code{pthread_mutex_unlock} as follows:
717 @smallexample
718 pthread_mutex_lock(&mut);
719 /* operate on x */
720 pthread_mutex_unlock(&mut);
721 @end smallexample
723 Mutex attributes can be specified at mutex creation time, by passing a
724 mutex attribute object as second argument to @code{pthread_mutex_init}.
725 Passing @code{NULL} is equivalent to passing a mutex attribute object
726 with all attributes set to their default values.
728 @comment pthread.h
729 @comment POSIX
730 @deftypefun int pthread_mutexattr_init (pthread_mutexattr_t *@var{attr})
731 @code{pthread_mutexattr_init} initializes the mutex attribute object
732 @var{attr} and fills it with default values for the attributes.
734 This function always returns 0.
735 @end deftypefun
737 @comment pthread.h
738 @comment POSIX
739 @deftypefun int pthread_mutexattr_destroy (pthread_mutexattr_t *@var{attr})
740 @code{pthread_mutexattr_destroy} destroys a mutex attribute object,
741 which must not be reused until it is
742 reinitialized. @code{pthread_mutexattr_destroy} does nothing in the
743 LinuxThreads implementation.
745 This function always returns 0.
746 @end deftypefun
748 LinuxThreads supports only one mutex attribute: the mutex type, which is
749 either @code{PTHREAD_MUTEX_ADAPTIVE_NP} for ``fast'' mutexes,
750 @code{PTHREAD_MUTEX_RECURSIVE_NP} for ``recursive'' mutexes,
751 @code{PTHREAD_MUTEX_TIMED_NP} for ``timed'' mutexes, or
752 @code{PTHREAD_MUTEX_ERRORCHECK_NP} for ``error checking'' mutexes.  As
753 the @code{NP} suffix indicates, this is a non-portable extension to the
754 POSIX standard and should not be employed in portable programs.
756 The mutex type determines what happens if a thread attempts to lock a
757 mutex it already owns with @code{pthread_mutex_lock}. If the mutex is of
758 the ``fast'' type, @code{pthread_mutex_lock} simply suspends the calling
759 thread forever.  If the mutex is of the ``error checking'' type,
760 @code{pthread_mutex_lock} returns immediately with the error code
761 @code{EDEADLK}.  If the mutex is of the ``recursive'' type, the call to
762 @code{pthread_mutex_lock} returns immediately with a success return
763 code. The number of times the thread owning the mutex has locked it is
764 recorded in the mutex. The owning thread must call
765 @code{pthread_mutex_unlock} the same number of times before the mutex
766 returns to the unlocked state.
768 The default mutex type is ``timed'', that is, @code{PTHREAD_MUTEX_TIMED_NP}.
769 @c This doesn't describe how a ``timed'' mutex behaves. FIXME
771 @comment pthread.h
772 @comment POSIX
773 @deftypefun int pthread_mutexattr_settype (pthread_mutexattr_t *@var{attr}, int @var{type})
774 @code{pthread_mutexattr_settype} sets the mutex type attribute in
775 @var{attr} to the value specified by @var{type}.
777 If @var{type} is not @code{PTHREAD_MUTEX_ADAPTIVE_NP},
778 @code{PTHREAD_MUTEX_RECURSIVE_NP}, @code{PTHREAD_MUTEX_TIMED_NP}, or
779 @code{PTHREAD_MUTEX_ERRORCHECK_NP}, this function will return
780 @code{EINVAL} and leave @var{attr} unchanged.
782 The standard Unix98 identifiers @code{PTHREAD_MUTEX_DEFAULT},
783 @code{PTHREAD_MUTEX_NORMAL}, @code{PTHREAD_MUTEX_RECURSIVE},
784 and @code{PTHREAD_MUTEX_ERRORCHECK} are also permitted.
786 @end deftypefun
788 @comment pthread.h
789 @comment POSIX
790 @deftypefun int pthread_mutexattr_gettype (const pthread_mutexattr_t *@var{attr}, int *@var{type})
791 @code{pthread_mutexattr_gettype} retrieves the current value of the
792 mutex type attribute in @var{attr} and stores it in the location pointed
793 to by @var{type}.
795 This function always returns 0.
796 @end deftypefun
798 @node Condition Variables
799 @section Condition Variables
801 A condition (short for ``condition variable'') is a synchronization
802 device that allows threads to suspend execution until some predicate on
803 shared data is satisfied. The basic operations on conditions are: signal
804 the condition (when the predicate becomes true), and wait for the
805 condition, suspending the thread execution until another thread signals
806 the condition.
808 A condition variable must always be associated with a mutex, to avoid
809 the race condition where a thread prepares to wait on a condition
810 variable and another thread signals the condition just before the first
811 thread actually waits on it.
813 @comment pthread.h
814 @comment POSIX
815 @deftypefun int pthread_cond_init (pthread_cond_t *@var{cond}, pthread_condattr_t *cond_@var{attr})
817 @code{pthread_cond_init} initializes the condition variable @var{cond},
818 using the condition attributes specified in @var{cond_attr}, or default
819 attributes if @var{cond_attr} is @code{NULL}. The LinuxThreads
820 implementation supports no attributes for conditions, hence the
821 @var{cond_attr} parameter is actually ignored.
823 Variables of type @code{pthread_cond_t} can also be initialized
824 statically, using the constant @code{PTHREAD_COND_INITIALIZER}.
826 This function always returns 0.
827 @end deftypefun
829 @comment pthread.h
830 @comment POSIX
831 @deftypefun int pthread_cond_signal (pthread_cond_t *@var{cond})
832 @code{pthread_cond_signal} restarts one of the threads that are waiting
833 on the condition variable @var{cond}. If no threads are waiting on
834 @var{cond}, nothing happens. If several threads are waiting on
835 @var{cond}, exactly one is restarted, but it is not specified which.
837 This function always returns 0.
838 @end deftypefun
840 @comment pthread.h
841 @comment POSIX
842 @deftypefun int pthread_cond_broadcast (pthread_cond_t *@var{cond})
843 @code{pthread_cond_broadcast} restarts all the threads that are waiting
844 on the condition variable @var{cond}. Nothing happens if no threads are
845 waiting on @var{cond}.
847 This function always returns 0.
848 @end deftypefun
850 @comment pthread.h
851 @comment POSIX
852 @deftypefun int pthread_cond_wait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex})
853 @code{pthread_cond_wait} atomically unlocks the @var{mutex} (as per
854 @code{pthread_unlock_mutex}) and waits for the condition variable
855 @var{cond} to be signaled. The thread execution is suspended and does
856 not consume any CPU time until the condition variable is signaled. The
857 @var{mutex} must be locked by the calling thread on entrance to
858 @code{pthread_cond_wait}. Before returning to the calling thread,
859 @code{pthread_cond_wait} re-acquires @var{mutex} (as per
860 @code{pthread_lock_mutex}).
862 Unlocking the mutex and suspending on the condition variable is done
863 atomically. Thus, if all threads always acquire the mutex before
864 signaling the condition, this guarantees that the condition cannot be
865 signaled (and thus ignored) between the time a thread locks the mutex
866 and the time it waits on the condition variable.
868 This function always returns 0.
869 @end deftypefun
871 @comment pthread.h
872 @comment POSIX
873 @deftypefun int pthread_cond_timedwait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime})
874 @code{pthread_cond_timedwait} atomically unlocks @var{mutex} and waits
875 on @var{cond}, as @code{pthread_cond_wait} does, but it also bounds the
876 duration of the wait. If @var{cond} has not been signaled before time
877 @var{abstime}, the mutex @var{mutex} is re-acquired and
878 @code{pthread_cond_timedwait} returns the error code @code{ETIMEDOUT}.
879 The wait can also be interrupted by a signal; in that case
880 @code{pthread_cond_timedwait} returns @code{EINTR}.
882 The @var{abstime} parameter specifies an absolute time, with the same
883 origin as @code{time} and @code{gettimeofday}: an @var{abstime} of 0
884 corresponds to 00:00:00 GMT, January 1, 1970.
885 @end deftypefun
887 @comment pthread.h
888 @comment POSIX
889 @deftypefun int pthread_cond_destroy (pthread_cond_t *@var{cond})
890 @code{pthread_cond_destroy} destroys the condition variable @var{cond},
891 freeing the resources it might hold.  If any threads are waiting on the
892 condition variable, @code{pthread_cond_destroy} leaves @var{cond}
893 untouched and returns @code{EBUSY}.  Otherwise it returns 0, and
894 @var{cond} must not be used again until it is reinitialized.
896 In the LinuxThreads implementation, no resources are associated with
897 condition variables, so @code{pthread_cond_destroy} actually does
898 nothing.
899 @end deftypefun
901 @code{pthread_cond_wait} and @code{pthread_cond_timedwait} are
902 cancellation points. If a thread is canceled while suspended in one of
903 these functions, the thread immediately resumes execution, relocks the
904 mutex specified by  @var{mutex}, and finally executes the cancellation.
905 Consequently, cleanup handlers are assured that @var{mutex} is locked
906 when they are called.
908 It is not safe to call the condition variable functions from a signal
909 handler. In particular, calling @code{pthread_cond_signal} or
910 @code{pthread_cond_broadcast} from a signal handler may deadlock the
911 calling thread.
913 Consider two shared variables @var{x} and @var{y}, protected by the
914 mutex @var{mut}, and a condition variable @var{cond} that is to be
915 signaled whenever @var{x} becomes greater than @var{y}.
917 @smallexample
918 int x,y;
919 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
920 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
921 @end smallexample
923 Waiting until @var{x} is greater than @var{y} is performed as follows:
925 @smallexample
926 pthread_mutex_lock(&mut);
927 while (x <= y) @{
928         pthread_cond_wait(&cond, &mut);
930 /* operate on x and y */
931 pthread_mutex_unlock(&mut);
932 @end smallexample
934 Modifications on @var{x} and @var{y} that may cause @var{x} to become greater than
935 @var{y} should signal the condition if needed:
937 @smallexample
938 pthread_mutex_lock(&mut);
939 /* modify x and y */
940 if (x > y) pthread_cond_broadcast(&cond);
941 pthread_mutex_unlock(&mut);
942 @end smallexample
944 If it can be proved that at most one waiting thread needs to be waken
945 up (for instance, if there are only two threads communicating through
946 @var{x} and @var{y}), @code{pthread_cond_signal} can be used as a slightly more
947 efficient alternative to @code{pthread_cond_broadcast}. In doubt, use
948 @code{pthread_cond_broadcast}.
950 To wait for @var{x} to becomes greater than @var{y} with a timeout of 5
951 seconds, do:
953 @smallexample
954 struct timeval now;
955 struct timespec timeout;
956 int retcode;
958 pthread_mutex_lock(&mut);
959 gettimeofday(&now);
960 timeout.tv_sec = now.tv_sec + 5;
961 timeout.tv_nsec = now.tv_usec * 1000;
962 retcode = 0;
963 while (x <= y && retcode != ETIMEDOUT) @{
964         retcode = pthread_cond_timedwait(&cond, &mut, &timeout);
966 if (retcode == ETIMEDOUT) @{
967         /* timeout occurred */
968 @} else @{
969         /* operate on x and y */
971 pthread_mutex_unlock(&mut);
972 @end smallexample
974 Condition attributes can be specified at condition creation time, by
975 passing a condition attribute object as second argument to
976 @code{pthread_cond_init}.  Passing @code{NULL} is equivalent to passing
977 a condition attribute object with all attributes set to their default
978 values.
980 The LinuxThreads implementation supports no attributes for
981 conditions. The functions on condition attributes are included only for
982 compliance with the POSIX standard.
984 @comment pthread.h
985 @comment POSIX
986 @deftypefun int pthread_condattr_init (pthread_condattr_t *@var{attr})
987 @deftypefunx int pthread_condattr_destroy (pthread_condattr_t *@var{attr})
988 @code{pthread_condattr_init} initializes the condition attribute object
989 @var{attr} and fills it with default values for the attributes.
990 @code{pthread_condattr_destroy} destroys the condition attribute object
991 @var{attr}.
993 Both functions do nothing in the LinuxThreads implementation.
995 @code{pthread_condattr_init} and @code{pthread_condattr_destroy} always
996 return 0.
997 @end deftypefun
999 @node POSIX Semaphores
1000 @section POSIX Semaphores
1002 @vindex SEM_VALUE_MAX
1003 Semaphores are counters for resources shared between threads. The
1004 basic operations on semaphores are: increment the counter atomically,
1005 and wait until the counter is non-null and decrement it atomically.
1007 Semaphores have a maximum value past which they cannot be incremented.
1008 The macro @code{SEM_VALUE_MAX} is defined to be this maximum value.  In
1009 the GNU C library, @code{SEM_VALUE_MAX} is equal to @code{INT_MAX}
1010 (@pxref{Range of Type}), but it may be much smaller on other systems.
1012 The pthreads library implements POSIX 1003.1b semaphores.  These should
1013 not be confused with System V semaphores (@code{ipc}, @code{semctl} and
1014 @code{semop}).
1015 @c !!! SysV IPC is not doc'd at all in our manual
1017 All the semaphore functions and macros are defined in @file{semaphore.h}.
1019 @comment semaphore.h
1020 @comment POSIX
1021 @deftypefun int sem_init (sem_t *@var{sem}, int @var{pshared}, unsigned int @var{value})
1022 @code{sem_init} initializes the semaphore object pointed to by
1023 @var{sem}. The count associated with the semaphore is set initially to
1024 @var{value}. The @var{pshared} argument indicates whether the semaphore
1025 is local to the current process (@var{pshared} is zero) or is to be
1026 shared between several processes (@var{pshared} is not zero).
1028 On success @code{sem_init} returns 0.  On failure it returns -1 and sets
1029 @var{errno} to one of the following values:
1031 @table @code
1032 @item EINVAL
1033 @var{value} exceeds the maximal counter value @code{SEM_VALUE_MAX}
1035 @item ENOSYS
1036 @var{pshared} is not zero.  LinuxThreads currently does not support
1037 process-shared semaphores.  (This will eventually change.)
1038 @end table
1039 @end deftypefun
1041 @comment semaphore.h
1042 @comment POSIX
1043 @deftypefun int sem_destroy (sem_t * @var{sem})
1044 @code{sem_destroy} destroys a semaphore object, freeing the resources it
1045 might hold.  If any threads are waiting on the semaphore when
1046 @code{sem_destroy} is called, it fails and sets @var{errno} to
1047 @code{EBUSY}.
1049 In the LinuxThreads implementation, no resources are associated with
1050 semaphore objects, thus @code{sem_destroy} actually does nothing except
1051 checking that no thread is waiting on the semaphore.  This will change
1052 when process-shared semaphores are implemented.
1053 @end deftypefun
1055 @comment semaphore.h
1056 @comment POSIX
1057 @deftypefun int sem_wait (sem_t * @var{sem})
1058 @code{sem_wait} suspends the calling thread until the semaphore pointed
1059 to by @var{sem} has non-zero count. It then atomically decreases the
1060 semaphore count.
1062 @code{sem_wait} is a cancellation point.  It always returns 0.
1063 @end deftypefun
1065 @comment semaphore.h
1066 @comment POSIX
1067 @deftypefun int sem_trywait (sem_t * @var{sem})
1068 @code{sem_trywait} is a non-blocking variant of @code{sem_wait}. If the
1069 semaphore pointed to by @var{sem} has non-zero count, the count is
1070 atomically decreased and @code{sem_trywait} immediately returns 0.  If
1071 the semaphore count is zero, @code{sem_trywait} immediately returns -1
1072 and sets errno to @code{EAGAIN}.
1073 @end deftypefun
1075 @comment semaphore.h
1076 @comment POSIX
1077 @deftypefun int sem_post (sem_t * @var{sem})
1078 @code{sem_post} atomically increases the count of the semaphore pointed to
1079 by @var{sem}. This function never blocks.
1081 @c !!! This para appears not to agree with the code.
1082 On processors supporting atomic compare-and-swap (Intel 486, Pentium and
1083 later, Alpha, PowerPC, MIPS II, Motorola 68k, Ultrasparc), the
1084 @code{sem_post} function is can safely be called from signal handlers.
1085 This is the only thread synchronization function provided by POSIX
1086 threads that is async-signal safe.  On the Intel 386 and earlier Sparc
1087 chips, the current LinuxThreads implementation of @code{sem_post} is not
1088 async-signal safe, because the hardware does not support the required
1089 atomic operations.
1091 @code{sem_post} always succeeds and returns 0, unless the semaphore
1092 count would exceed @code{SEM_VALUE_MAX} after being incremented.  In
1093 that case @code{sem_post} returns -1 and sets @var{errno} to
1094 @code{EINVAL}.  The semaphore count is left unchanged.
1095 @end deftypefun
1097 @comment semaphore.h
1098 @comment POSIX
1099 @deftypefun int sem_getvalue (sem_t * @var{sem}, int * @var{sval})
1100 @code{sem_getvalue} stores in the location pointed to by @var{sval} the
1101 current count of the semaphore @var{sem}.  It always returns 0.
1102 @end deftypefun
1104 @node Thread-Specific Data
1105 @section Thread-Specific Data
1107 Programs often need global or static variables that have different
1108 values in different threads. Since threads share one memory space, this
1109 cannot be achieved with regular variables. Thread-specific data is the
1110 POSIX threads answer to this need.
1112 Each thread possesses a private memory block, the thread-specific data
1113 area, or TSD area for short. This area is indexed by TSD keys. The TSD
1114 area associates values of type @code{void *} to TSD keys. TSD keys are
1115 common to all threads, but the value associated with a given TSD key can
1116 be different in each thread.
1118 For concreteness, the TSD areas can be viewed as arrays of @code{void *}
1119 pointers, TSD keys as integer indices into these arrays, and the value
1120 of a TSD key as the value of the corresponding array element in the
1121 calling thread.
1123 When a thread is created, its TSD area initially associates @code{NULL}
1124 with all keys.
1126 @comment pthread.h
1127 @comment POSIX
1128 @deftypefun int pthread_key_create (pthread_key_t *@var{key}, void (*destr_function) (void *))
1129 @code{pthread_key_create} allocates a new TSD key. The key is stored in
1130 the location pointed to by @var{key}. There is a limit of
1131 @code{PTHREAD_KEYS_MAX} on the number of keys allocated at a given
1132 time. The value initially associated with the returned key is
1133 @code{NULL} in all currently executing threads.
1135 The @var{destr_function} argument, if not @code{NULL}, specifies a
1136 destructor function associated with the key. When a thread terminates
1137 via @code{pthread_exit} or by cancellation, @var{destr_function} is
1138 called on the value associated with the key in that thread. The
1139 @var{destr_function} is not called if a key is deleted with
1140 @code{pthread_key_delete} or a value is changed with
1141 @code{pthread_setspecific}.  The order in which destructor functions are
1142 called at thread termination time is unspecified.
1144 Before the destructor function is called, the @code{NULL} value is
1145 associated with the key in the current thread.  A destructor function
1146 might, however, re-associate non-@code{NULL} values to that key or some
1147 other key.  To deal with this, if after all the destructors have been
1148 called for all non-@code{NULL} values, there are still some
1149 non-@code{NULL} values with associated destructors, then the process is
1150 repeated.  The LinuxThreads implementation stops the process after
1151 @code{PTHREAD_DESTRUCTOR_ITERATIONS} iterations, even if some
1152 non-@code{NULL} values with associated descriptors remain.  Other
1153 implementations may loop indefinitely.
1155 @code{pthread_key_create} returns 0 unless @code{PTHREAD_KEYS_MAX} keys
1156 have already been allocated, in which case it fails and returns
1157 @code{EAGAIN}.
1158 @end deftypefun
1161 @comment pthread.h
1162 @comment POSIX
1163 @deftypefun int pthread_key_delete (pthread_key_t @var{key})
1164 @code{pthread_key_delete} deallocates a TSD key. It does not check
1165 whether non-@code{NULL} values are associated with that key in the
1166 currently executing threads, nor call the destructor function associated
1167 with the key.
1169 If there is no such key @var{key}, it returns @code{EINVAL}.  Otherwise
1170 it returns 0.
1171 @end deftypefun
1173 @comment pthread.h
1174 @comment POSIX
1175 @deftypefun int pthread_setspecific (pthread_key_t @var{key}, const void *@var{pointer})
1176 @code{pthread_setspecific} changes the value associated with @var{key}
1177 in the calling thread, storing the given @var{pointer} instead.
1179 If there is no such key @var{key}, it returns @code{EINVAL}.  Otherwise
1180 it returns 0.
1181 @end deftypefun
1183 @comment pthread.h
1184 @comment POSIX
1185 @deftypefun {void *} pthread_getspecific (pthread_key_t @var{key})
1186 @code{pthread_getspecific} returns the value currently associated with
1187 @var{key} in the calling thread.
1189 If there is no such key @var{key}, it returns @code{NULL}.
1190 @end deftypefun
1192 The following code fragment allocates a thread-specific array of 100
1193 characters, with automatic reclaimation at thread exit:
1195 @smallexample
1196 /* Key for the thread-specific buffer */
1197 static pthread_key_t buffer_key;
1199 /* Once-only initialisation of the key */
1200 static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
1202 /* Allocate the thread-specific buffer */
1203 void buffer_alloc(void)
1205   pthread_once(&buffer_key_once, buffer_key_alloc);
1206   pthread_setspecific(buffer_key, malloc(100));
1209 /* Return the thread-specific buffer */
1210 char * get_buffer(void)
1212   return (char *) pthread_getspecific(buffer_key);
1215 /* Allocate the key */
1216 static void buffer_key_alloc()
1218   pthread_key_create(&buffer_key, buffer_destroy);
1221 /* Free the thread-specific buffer */
1222 static void buffer_destroy(void * buf)
1224   free(buf);
1226 @end smallexample
1228 @node Threads and Signal Handling
1229 @section Threads and Signal Handling
1231 @comment pthread.h
1232 @comment POSIX
1233 @deftypefun int pthread_sigmask (int @var{how}, const sigset_t *@var{newmask}, sigset_t *@var{oldmask})
1234 @code{pthread_sigmask} changes the signal mask for the calling thread as
1235 described by the @var{how} and @var{newmask} arguments. If @var{oldmask}
1236 is not @code{NULL}, the previous signal mask is stored in the location
1237 pointed to by @var{oldmask}.
1239 The meaning of the @var{how} and @var{newmask} arguments is the same as
1240 for @code{sigprocmask}. If @var{how} is @code{SIG_SETMASK}, the signal
1241 mask is set to @var{newmask}. If @var{how} is @code{SIG_BLOCK}, the
1242 signals specified to @var{newmask} are added to the current signal mask.
1243 If @var{how} is @code{SIG_UNBLOCK}, the signals specified to
1244 @var{newmask} are removed from the current signal mask.
1246 Recall that signal masks are set on a per-thread basis, but signal
1247 actions and signal handlers, as set with @code{sigaction}, are shared
1248 between all threads.
1250 The @code{pthread_sigmask} function returns 0 on success, and one of the
1251 following error codes on error:
1252 @table @code
1253 @item EINVAL
1254 @var{how} is not one of @code{SIG_SETMASK}, @code{SIG_BLOCK}, or @code{SIG_UNBLOCK}
1256 @item EFAULT
1257 @var{newmask} or @var{oldmask} point to invalid addresses
1258 @end table
1259 @end deftypefun
1261 @comment pthread.h
1262 @comment POSIX
1263 @deftypefun int pthread_kill (pthread_t @var{thread}, int @var{signo})
1264 @code{pthread_kill} sends signal number @var{signo} to the thread
1265 @var{thread}.  The signal is delivered and handled as described in
1266 @ref{Signal Handling}.
1268 @code{pthread_kill} returns 0 on success, one of the following error codes
1269 on error:
1270 @table @code
1271 @item EINVAL
1272 @var{signo} is not a valid signal number
1274 @item ESRCH
1275 The thread @var{thread} does not exist (e.g. it has already terminated)
1276 @end table
1277 @end deftypefun
1279 @comment pthread.h
1280 @comment POSIX
1281 @deftypefun int sigwait (const sigset_t *@var{set}, int *@var{sig})
1282 @code{sigwait} suspends the calling thread until one of the signals in
1283 @var{set} is delivered to the calling thread. It then stores the number
1284 of the signal received in the location pointed to by @var{sig} and
1285 returns. The signals in @var{set} must be blocked and not ignored on
1286 entrance to @code{sigwait}. If the delivered signal has a signal handler
1287 function attached, that function is @emph{not} called.
1289 @code{sigwait} is a cancellation point.  It always returns 0.
1290 @end deftypefun
1292 For @code{sigwait} to work reliably, the signals being waited for must be
1293 blocked in all threads, not only in the calling thread, since
1294 otherwise the POSIX semantics for signal delivery do not guarantee
1295 that it's the thread doing the @code{sigwait} that will receive the signal.
1296 The best way to achieve this is block those signals before any threads
1297 are created, and never unblock them in the program other than by
1298 calling @code{sigwait}.
1300 Signal handling in LinuxThreads departs significantly from the POSIX
1301 standard. According to the standard, ``asynchronous'' (external) signals
1302 are addressed to the whole process (the collection of all threads),
1303 which then delivers them to one particular thread. The thread that
1304 actually receives the signal is any thread that does not currently block
1305 the signal.
1307 In LinuxThreads, each thread is actually a kernel process with its own
1308 PID, so external signals are always directed to one particular thread.
1309 If, for instance, another thread is blocked in @code{sigwait} on that
1310 signal, it will not be restarted.
1312 The LinuxThreads implementation of @code{sigwait} installs dummy signal
1313 handlers for the signals in @var{set} for the duration of the
1314 wait. Since signal handlers are shared between all threads, other
1315 threads must not attach their own signal handlers to these signals, or
1316 alternatively they should all block these signals (which is recommended
1317 anyway).
1319 @node Threads and Fork
1320 @section Threads and Fork
1322 It's not intuitively obvious what should happen when a multi-threaded POSIX
1323 process calls @code{fork}. Not only are the semantics tricky, but you may
1324 need to write code that does the right thing at fork time even if that code
1325 doesn't use the @code{fork} function. Moreover, you need to be aware of
1326 interaction between @code{fork} and some library features like
1327 @code{pthread_once} and stdio streams.
1329 When @code{fork} is called by one of the threads of a process, it creates a new
1330 process which is copy of the  calling process. Effectively, in addition to
1331 copying certain system objects, the function takes a snapshot of the memory
1332 areas of the parent process, and creates identical areas in the child.
1333 To make matters more complicated, with threads it's possible for two or more
1334 threads to concurrently call fork to create two or more child processes.
1336 The child process has a copy of the address space of the parent, but it does
1337 not inherit any of its threads. Execution of the child process is carried out
1338 by a new thread which returns from @code{fork} function with a return value of
1339 zero; it is the only thread in the child process.  Because threads are not
1340 inherited across fork, issues arise. At the time of the call to @code{fork},
1341 threads in the parent process other than the one calling @code{fork} may have
1342 been executing critical regions of code.  As a result, the child process may
1343 get a copy of objects that are not in a well-defined state.  This potential
1344 problem affects all components of the program.
1346 Any program component which will continue being used in a child process must
1347 correctly handle its state during @code{fork}. For this purpose, the POSIX
1348 interface provides the special function @code{pthread_atfork} for installing
1349 pointers to handler functions which are called from within @code{fork}.
1351 @comment pthread.h
1352 @comment POSIX
1353 @deftypefun int pthread_atfork (void (*@var{prepare})(void), void (*@var{parent})(void), void (*@var{child})(void))
1355 @code{pthread_atfork} registers handler functions to be called just
1356 before and just after a new process is created with @code{fork}. The
1357 @var{prepare} handler will be called from the parent process, just
1358 before the new process is created. The @var{parent} handler will be
1359 called from the parent process, just before @code{fork} returns. The
1360 @var{child} handler will be called from the child process, just before
1361 @code{fork} returns.
1363 @code{pthread_atfork} returns 0 on success and a non-zero error code on
1364 error.
1366 One or more of the three handlers @var{prepare}, @var{parent} and
1367 @var{child} can be given as @code{NULL}, meaning that no handler needs
1368 to be called at the corresponding point.
1370 @code{pthread_atfork} can be called several times to install several
1371 sets of handlers. At @code{fork} time, the @var{prepare} handlers are
1372 called in LIFO order (last added with @code{pthread_atfork}, first
1373 called before @code{fork}), while the @var{parent} and @var{child}
1374 handlers are called in FIFO order (first added, first called).
1376 If there is insufficient memory available to register the handlers,
1377 @code{pthread_atfork} fails and returns @code{ENOMEM}.  Otherwise it
1378 returns 0.
1380 The functions @code{fork} and @code{pthread_atfork} must not be regarded as
1381 reentrant from the context of the handlers.  That is to say, if a
1382 @code{pthread_atfork} handler invoked from within @code{fork} calls
1383 @code{pthread_atfork} or @code{fork}, the behavior is undefined.
1385 Registering a triplet of handlers is an atomic operation with respect to fork.
1386 If new handlers are registered at about the same time as a fork occurs, either
1387 all three handlers will be called, or none of them will be called.
1389 The handlers are inherited by the child process, and there is no
1390 way to remove them, short of using @code{exec} to load a new
1391 pocess image.
1393 @end deftypefun
1395 To understand the purpose of @code{pthread_atfork}, recall that
1396 @code{fork} duplicates the whole memory space, including mutexes in
1397 their current locking state, but only the calling thread: other threads
1398 are not running in the child process.  The mutexes are not usable after
1399 the @code{fork} and must be initialized with @code{pthread_mutex_init}
1400 in the child process.  This is a limitation of the current
1401 implementation and might or might not be present in future versions.
1403 To avoid this, install handlers with @code{pthread_atfork} as follows: have the
1404 @var{prepare} handler lock the mutexes (in locking order), and the
1405 @var{parent} handler unlock the mutexes. The @var{child} handler should reset
1406 the mutexes using @code{pthread_mutex_init}, as well as any other
1407 synchronization objects such as condition variables.
1409 Locking the global mutexes before the fork ensures that all other threads are
1410 locked out of the critical regions of code protected by those mutexes.  Thus
1411 when @code{fork} takes a snapshot of the parent's address space, that snapshot
1412 will copy valid, stable data.  Resetting the synchronization objects in the
1413 child process will ensure they are properly cleansed of any artifacts from the
1414 threading subsystem of the parent process. For example, a mutex may inherit
1415 a wait queue of threads waiting for the lock; this wait queue makes no sense
1416 in the child process. Initializing the mutex takes care of this.
1418 @node Streams and Fork
1419 @section Streams and Fork
1421 The GNU standard I/O library has an internal mutex which guards the internal
1422 linked list of all standard C FILE objects. This mutex is properly taken care
1423 of during @code{fork} so that the child receives an intact copy of the list.
1424 This allows the @code{fopen} function, and related stream-creating functions,
1425 to work correctly in the child process, since these functions need to insert
1426 into the list.
1428 However, the individual stream locks are not completely taken care of.  Thus
1429 unless the multithreaded application takes special precautions in its use of
1430 @code{fork}, the child process might not be able to safely use the streams that
1431 it inherited from the parent.   In general, for any given open stream in the
1432 parent that is to be used by the child process, the application must ensure
1433 that that stream is not in use by another thread when @code{fork} is called.
1434 Otherwise an inconsistent copy of the stream object be produced. An easy way to
1435 ensure this is to use @code{flockfile} to lock the stream prior to calling
1436 @code{fork} and then unlock it with @code{funlockfile} inside the parent
1437 process, provided that the parent's threads properly honor these locks.
1438 Nothing special needs to be done in the child process, since the library
1439 internally resets all stream locks.
1441 Note that the stream locks are not shared between the parent and child.
1442 For example, even if you ensure that, say, the stream @code{stdout} is properly
1443 treated and can be safely used in the child, the stream locks do not provide
1444 an exclusion mechanism between the parent and child. If both processes write
1445 to @code{stdout}, strangely interleaved output may result regardless of
1446 the explicit use of @code{flockfile} or implicit locks.
1448 Also note that these provisions are a GNU extension; other systems might not
1449 provide any way for streams to be used in the child of a multithreaded process.
1450 POSIX requires that such a child process confines itself to calling only
1451 asynchronous safe functions, which excludes much of the library, including
1452 standard I/O.
1454 @node Miscellaneous Thread Functions
1455 @section Miscellaneous Thread Functions
1457 @comment pthread.h
1458 @comment POSIX
1459 @deftypefun {pthread_t} pthread_self (@var{void})
1460 @code{pthread_self} returns the thread identifier for the calling thread.
1461 @end deftypefun
1463 @comment pthread.h
1464 @comment POSIX
1465 @deftypefun int pthread_equal (pthread_t thread1, pthread_t thread2)
1466 @code{pthread_equal} determines if two thread identifiers refer to the same
1467 thread.
1469 A non-zero value is returned if @var{thread1} and @var{thread2} refer to
1470 the same thread. Otherwise, 0 is returned.
1471 @end deftypefun
1473 @comment pthread.h
1474 @comment POSIX
1475 @deftypefun int pthread_detach (pthread_t @var{th})
1476 @code{pthread_detach} puts the thread @var{th} in the detached
1477 state. This guarantees that the memory resources consumed by @var{th}
1478 will be freed immediately when @var{th} terminates. However, this
1479 prevents other threads from synchronizing on the termination of @var{th}
1480 using @code{pthread_join}.
1482 A thread can be created initially in the detached state, using the
1483 @code{detachstate} attribute to @code{pthread_create}. In contrast,
1484 @code{pthread_detach} applies to threads created in the joinable state,
1485 and which need to be put in the detached state later.
1487 After @code{pthread_detach} completes, subsequent attempts to perform
1488 @code{pthread_join} on @var{th} will fail. If another thread is already
1489 joining the thread @var{th} at the time @code{pthread_detach} is called,
1490 @code{pthread_detach} does nothing and leaves @var{th} in the joinable
1491 state.
1493 On success, 0 is returned. On error, one of the following codes is
1494 returned:
1495 @table @code
1496 @item ESRCH
1497 No thread could be found corresponding to that specified by @var{th}
1498 @item EINVAL
1499 The thread @var{th} is already in the detached state
1500 @end table
1501 @end deftypefun
1503 @comment pthread.h
1504 @comment GNU
1505 @deftypefun void pthread_kill_other_threads_np (@var{void})
1506 @code{pthread_kill_other_threads_np} is a non-portable LinuxThreads extension.
1507 It causes all threads in the program to terminate immediately, except
1508 the calling thread which proceeds normally. It is intended to be
1509 called just before a thread calls one of the @code{exec} functions,
1510 e.g. @code{execve}.
1512 Termination of the other threads is not performed through
1513 @code{pthread_cancel} and completely bypasses the cancellation
1514 mechanism. Hence, the current settings for cancellation state and
1515 cancellation type are ignored, and the cleanup handlers are not
1516 executed in the terminated threads.
1518 According to POSIX 1003.1c, a successful @code{exec*} in one of the
1519 threads should automatically terminate all other threads in the program.
1520 This behavior is not yet implemented in LinuxThreads.  Calling
1521 @code{pthread_kill_other_threads_np} before @code{exec*} achieves much
1522 of the same behavior, except that if @code{exec*} ultimately fails, then
1523 all other threads are already killed.
1524 @end deftypefun
1526 @comment pthread.h
1527 @comment POSIX
1528 @deftypefun int pthread_once (pthread_once_t *once_@var{control}, void (*@var{init_routine}) (void))
1530 The purpose of @code{pthread_once} is to ensure that a piece of
1531 initialization code is executed at most once. The @var{once_control}
1532 argument points to a static or extern variable statically initialized
1533 to @code{PTHREAD_ONCE_INIT}.
1535 The first time @code{pthread_once} is called with a given
1536 @var{once_control} argument, it calls @var{init_routine} with no
1537 argument and changes the value of the @var{once_control} variable to
1538 record that initialization has been performed. Subsequent calls to
1539 @code{pthread_once} with the same @code{once_control} argument do
1540 nothing.
1542 If a thread is cancelled while executing @var{init_routine}
1543 the state of the @var{once_control} variable is reset so that
1544 a future call to @code{pthread_once} will call the routine again.
1546 If the process forks while one or more threads are executing
1547 @code{pthread_once} initialization routines, the states of their respective
1548 @var{once_control} variables will appear to be reset in the child process so
1549 that if the child calls @code{pthread_once}, the routines will be executed.
1551 @code{pthread_once} always returns 0.
1552 @end deftypefun
1554 @comment pthread.h
1555 @comment POSIX
1556 @deftypefun int pthread_setschedparam (pthread_t target_@var{thread}, int @var{policy}, const struct sched_param *@var{param})
1558 @code{pthread_setschedparam} sets the scheduling parameters for the
1559 thread @var{target_thread} as indicated by @var{policy} and
1560 @var{param}. @var{policy} can be either @code{SCHED_OTHER} (regular,
1561 non-realtime scheduling), @code{SCHED_RR} (realtime, round-robin) or
1562 @code{SCHED_FIFO} (realtime, first-in first-out). @var{param} specifies
1563 the scheduling priority for the two realtime policies.  See
1564 @code{sched_setpolicy} for more information on scheduling policies.
1566 The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
1567 are available only to processes with superuser privileges.
1569 On success, @code{pthread_setschedparam} returns 0.  On error it returns
1570 one of the following codes:
1571 @table @code
1572 @item EINVAL
1573 @var{policy} is not one of @code{SCHED_OTHER}, @code{SCHED_RR},
1574 @code{SCHED_FIFO}, or the priority value specified by @var{param} is not
1575 valid for the specified policy
1577 @item EPERM
1578 Realtime scheduling was requested but the calling process does not have
1579 sufficient privileges.
1581 @item ESRCH
1582 The @var{target_thread} is invalid or has already terminated
1584 @item EFAULT
1585 @var{param} points outside the process memory space
1586 @end table
1587 @end deftypefun
1589 @comment pthread.h
1590 @comment POSIX
1591 @deftypefun int pthread_getschedparam (pthread_t target_@var{thread}, int *@var{policy}, struct sched_param *@var{param})
1593 @code{pthread_getschedparam} retrieves the scheduling policy and
1594 scheduling parameters for the thread @var{target_thread} and stores them
1595 in the locations pointed to by @var{policy} and @var{param},
1596 respectively.
1598 @code{pthread_getschedparam} returns 0 on success, or one of the
1599 following error codes on failure:
1600 @table @code
1601 @item ESRCH
1602 The @var{target_thread} is invalid or has already terminated.
1604 @item EFAULT
1605 @var{policy} or @var{param} point outside the process memory space.
1607 @end table
1608 @end deftypefun
1610 @comment pthread.h
1611 @comment POSIX
1612 @deftypefun int pthread_setconcurrency (int @var{level})
1613 @code{pthread_setconcurrency} is unused in LinuxThreads due to the lack
1614 of a mapping of user threads to kernel threads.  It exists for source
1615 compatibility.  It does store the value @var{level} so that it can be
1616 returned by a subsequent call to @code{pthread_getconcurrency}.  It takes
1617 no other action however.
1618 @end deftypefun
1620 @comment pthread.h
1621 @comment POSIX
1622 @deftypefun int pthread_getconcurrency ()
1623 @code{pthread_getconcurrency} is unused in LinuxThreads due to the lack
1624 of a mapping of user threads to kernel threads.  It exists for source
1625 compatibility.  However, it will return the value that was set by the
1626 last call to @code{pthread_setconcurrency}.
1627 @end deftypefun