Update.
[glibc.git] / linuxthreads / linuxthreads.texi
blobc6a3253026a90d0545bd3d1707dd163a80ca8c0f
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                                   cancelled.
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 cancelled.
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 cancelled.
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_setinheritsched
185 @findex pthread_attr_setschedparam
186 @findex pthread_attr_setschedpolicy
187 @findex pthread_attr_setscope
188 @comment pthread.h
189 @comment POSIX
190 @deftypefun int pthread_attr_set@var{attr} (pthread_attr_t *@var{obj}, int @var{value})
191 Set attribute @var{attr} to @var{value} in the attribute object pointed
192 to by @var{obj}.  See below for a list of possible attributes and the
193 values they can take.
195 On success, these functions return 0.  If @var{value} is not meaningful
196 for the @var{attr} being modified, they will return the error code
197 @code{EINVAL}.  Some of the functions have other failure modes; see
198 below.
199 @end deftypefun
201 @findex pthread_attr_getinheritsched
202 @findex pthread_attr_getschedparam
203 @findex pthread_attr_getschedpolicy
204 @findex pthread_attr_getscope
205 @comment pthread.h
206 @comment POSIX
207 @deftypefun int pthread_attr_get@var{attr} (const pthread_attr_t *@var{obj}, int *@var{value})
208 Store the current setting of @var{attr} in @var{obj} into the variable
209 pointed to by @var{value}.
211 These functions always return 0.
212 @end deftypefun
214 The following thread attributes are supported:
215 @table @samp
216 @item detachstate
217 Choose whether the thread is created in the joinable state (value
218 @code{PTHREAD_CREATE_JOINABLE}) or in the detached state
219 (@code{PTHREAD_CREATE_DETACHED}).  The default is
220 @code{PTHREAD_CREATE_JOINABLE}.
222 In the joinable state, another thread can synchronize on the thread
223 termination and recover its termination code using @code{pthread_join},
224 but some of the thread resources are kept allocated after the thread
225 terminates, and reclaimed only when another thread performs
226 @code{pthread_join} on that thread.
228 In the detached state, the thread resources are immediately freed when
229 it terminates, but @code{pthread_join} cannot be used to synchronize on
230 the thread termination.
232 A thread created in the joinable state can later be put in the detached
233 thread using @code{pthread_detach}.
235 @item schedpolicy
236 Select the scheduling policy for the thread: one of @code{SCHED_OTHER}
237 (regular, non-realtime scheduling), @code{SCHED_RR} (realtime,
238 round-robin) or @code{SCHED_FIFO} (realtime, first-in first-out).
239 The default is @code{SCHED_OTHER}.
240 @c Not doc'd in our manual: FIXME.
241 @c See @code{sched_setpolicy} for more information on scheduling policies.
243 The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
244 are available only to processes with superuser privileges.
245 @code{pthread_attr_setschedparam} will fail and return @code{ENOTSUP} if
246 you try to set a realtime policy when you are unprivileged.
248 The scheduling policy of a thread can be changed after creation with
249 @code{pthread_setschedparam}.
251 @item schedparam
252 Change the scheduling parameter (the scheduling priority)
253 for the thread.  The default is 0.
255 This attribute is not significant if the scheduling policy is
256 @code{SCHED_OTHER}; it only matters for the realtime policies
257 @code{SCHED_RR} and @code{SCHED_FIFO}.
259 The scheduling priority of a thread can be changed after creation with
260 @code{pthread_setschedparam}.
262 @item inheritsched
263 Choose whether the scheduling policy and scheduling parameter for the
264 newly created thread are determined by the values of the
265 @var{schedpolicy} and @var{schedparam} attributes (value
266 @code{PTHREAD_EXPLICIT_SCHED}) or are inherited from the parent thread
267 (value @code{PTHREAD_INHERIT_SCHED}).  The default is
268 @code{PTHREAD_EXPLICIT_SCHED}.
270 @item scope
271 Choose the scheduling contention scope for the created thread.  The
272 default is @code{PTHREAD_SCOPE_SYSTEM}, meaning that the threads contend
273 for CPU time with all processes running on the machine. In particular,
274 thread priorities are interpreted relative to the priorities of all
275 other processes on the machine. The other possibility,
276 @code{PTHREAD_SCOPE_PROCESS}, means that scheduling contention occurs
277 only between the threads of the running process: thread priorities are
278 interpreted relative to the priorities of the other threads of the
279 process, regardless of the priorities of other processes.
281 @code{PTHREAD_SCOPE_PROCESS} is not supported in LinuxThreads.  If you
282 try to set the scope to this value @code{pthread_attr_setscope} will
283 fail and return @code{ENOTSUP}.
284 @end table
286 @node Cancellation
287 @section Cancellation
289 Cancellation is the mechanism by which a thread can terminate the
290 execution of another thread. More precisely, a thread can send a
291 cancellation request to another thread. Depending on its settings, the
292 target thread can then either ignore the request, honor it immediately,
293 or defer it till it reaches a cancellation point.  When threads are
294 first created by @code{pthread_create}, they always defer cancellation
295 requests.
297 When a thread eventually honors a cancellation request, it behaves as if
298 @code{pthread_exit(PTHREAD_CANCELED)} was called.  All cleanup handlers
299 are executed in reverse order, finalization functions for
300 thread-specific data are called, and finally the thread stops executing.
301 If the cancelled thread was joinable, the return value
302 @code{PTHREAD_CANCELED} is provided to whichever thread calls
303 @var{pthread_join} on it. See @code{pthread_exit} for more information.
305 Cancellation points are the points where the thread checks for pending
306 cancellation requests and performs them.  The POSIX threads functions
307 @code{pthread_join}, @code{pthread_cond_wait},
308 @code{pthread_cond_timedwait}, @code{pthread_testcancel},
309 @code{sem_wait}, and @code{sigwait} are cancellation points.  In
310 addition, these system calls are cancellation points:
312 @multitable @columnfractions .33 .33 .33
313 @item @t{accept}        @tab @t{open}           @tab @t{sendmsg}
314 @item @t{close}         @tab @t{pause}          @tab @t{sendto}
315 @item @t{connect}       @tab @t{read}           @tab @t{system}
316 @item @t{fcntl}         @tab @t{recv}           @tab @t{tcdrain}
317 @item @t{fsync}         @tab @t{recvfrom}       @tab @t{wait}
318 @item @t{lseek}         @tab @t{recvmsg}        @tab @t{waitpid}
319 @item @t{msync}         @tab @t{send}           @tab @t{write}
320 @item @t{nanosleep}
321 @end multitable
323 @noindent
324 All library functions that call these functions (such as
325 @code{printf}) are also cancellation points.
327 @comment pthread.h
328 @comment POSIX
329 @deftypefun int pthread_setcancelstate (int @var{state}, int *@var{oldstate})
330 @code{pthread_setcancelstate} changes the cancellation state for the
331 calling thread -- that is, whether cancellation requests are ignored or
332 not. The @var{state} argument is the new cancellation state: either
333 @code{PTHREAD_CANCEL_ENABLE} to enable cancellation, or
334 @code{PTHREAD_CANCEL_DISABLE} to disable cancellation (cancellation
335 requests are ignored).
337 If @var{oldstate} is not @code{NULL}, the previous cancellation state is
338 stored in the location pointed to by @var{oldstate}, and can thus be
339 restored later by another call to @code{pthread_setcancelstate}.
341 If the @var{state} argument is not @code{PTHREAD_CANCEL_ENABLE} or
342 @code{PTHREAD_CANCEL_DISABLE}, @code{pthread_setcancelstate} fails and
343 returns @code{EINVAL}.  Otherwise it returns 0.
344 @end deftypefun
346 @comment pthread.h
347 @comment POSIX
348 @deftypefun int pthread_setcanceltype (int @var{type}, int *@var{oldtype})
349 @code{pthread_setcanceltype} changes the type of responses to
350 cancellation requests for the calling thread: asynchronous (immediate)
351 or deferred.  The @var{type} argument is the new cancellation type:
352 either @code{PTHREAD_CANCEL_ASYNCHRONOUS} to cancel the calling thread
353 as soon as the cancellation request is received, or
354 @code{PTHREAD_CANCEL_DEFERRED} to keep the cancellation request pending
355 until the next cancellation point. If @var{oldtype} is not @code{NULL},
356 the previous cancellation state is stored in the location pointed to by
357 @var{oldtype}, and can thus be restored later by another call to
358 @code{pthread_setcanceltype}.
360 If the @var{type} argument is not @code{PTHREAD_CANCEL_DEFERRED} or
361 @code{PTHREAD_CANCEL_ASYNCHRONOUS}, @code{pthread_setcanceltype} fails
362 and returns @code{EINVAL}.  Otherwise it returns 0.
363 @end deftypefun
365 @comment pthread.h
366 @comment POSIX
367 @deftypefun void pthread_testcancel (@var{void})
368 @code{pthread_testcancel} does nothing except testing for pending
369 cancellation and executing it. Its purpose is to introduce explicit
370 checks for cancellation in long sequences of code that do not call
371 cancellation point functions otherwise.
372 @end deftypefun
374 @node Cleanup Handlers
375 @section Cleanup Handlers
377 Cleanup handlers are functions that get called when a thread terminates,
378 either by calling @code{pthread_exit} or because of
379 cancellation. Cleanup handlers are installed and removed following a
380 stack-like discipline.
382 The purpose of cleanup handlers is to free the resources that a thread
383 may hold at the time it terminates. In particular, if a thread exits or
384 is cancelled while it owns a locked mutex, the mutex will remain locked
385 forever and prevent other threads from executing normally. The best way
386 to avoid this is, just before locking the mutex, to install a cleanup
387 handler whose effect is to unlock the mutex. Cleanup handlers can be
388 used similarly to free blocks allocated with @code{malloc} or close file
389 descriptors on thread termination.
391 Here is how to lock a mutex @var{mut} in such a way that it will be
392 unlocked if the thread is canceled while @var{mut} is locked:
394 @smallexample
395 pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
396 pthread_mutex_lock(&mut);
397 /* do some work */
398 pthread_mutex_unlock(&mut);
399 pthread_cleanup_pop(0);
400 @end smallexample
402 Equivalently, the last two lines can be replaced by
404 @smallexample
405 pthread_cleanup_pop(1);
406 @end smallexample
408 Notice that the code above is safe only in deferred cancellation mode
409 (see @code{pthread_setcanceltype}). In asynchronous cancellation mode, a
410 cancellation can occur between @code{pthread_cleanup_push} and
411 @code{pthread_mutex_lock}, or between @code{pthread_mutex_unlock} and
412 @code{pthread_cleanup_pop}, resulting in both cases in the thread trying
413 to unlock a mutex not locked by the current thread. This is the main
414 reason why asynchronous cancellation is difficult to use.
416 If the code above must also work in asynchronous cancellation mode,
417 then it must switch to deferred mode for locking and unlocking the
418 mutex:
420 @smallexample
421 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
422 pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
423 pthread_mutex_lock(&mut);
424 /* do some work */
425 pthread_cleanup_pop(1);
426 pthread_setcanceltype(oldtype, NULL);
427 @end smallexample
429 The code above can be rewritten in a more compact and efficient way,
430 using the non-portable functions @code{pthread_cleanup_push_defer_np}
431 and @code{pthread_cleanup_pop_restore_np}:
433 @smallexample
434 pthread_cleanup_push_defer_np(pthread_mutex_unlock, (void *) &mut);
435 pthread_mutex_lock(&mut);
436 /* do some work */
437 pthread_cleanup_pop_restore_np(1);
438 @end smallexample
440 @comment pthread.h
441 @comment POSIX
442 @deftypefun void pthread_cleanup_push (void (*@var{routine}) (void *), void *@var{arg})
444 @code{pthread_cleanup_push} installs the @var{routine} function with
445 argument @var{arg} as a cleanup handler. From this point on to the
446 matching @code{pthread_cleanup_pop}, the function @var{routine} will be
447 called with arguments @var{arg} when the thread terminates, either
448 through @code{pthread_exit} or by cancellation. If several cleanup
449 handlers are active at that point, they are called in LIFO order: the
450 most recently installed handler is called first.
451 @end deftypefun
453 @comment pthread.h
454 @comment POSIX
455 @deftypefun void pthread_cleanup_pop (int @var{execute})
456 @code{pthread_cleanup_pop} removes the most recently installed cleanup
457 handler. If the @var{execute} argument is not 0, it also executes the
458 handler, by calling the @var{routine} function with arguments
459 @var{arg}. If the @var{execute} argument is 0, the handler is only
460 removed but not executed.
461 @end deftypefun
463 Matching pairs of @code{pthread_cleanup_push} and
464 @code{pthread_cleanup_pop} must occur in the same function, at the same
465 level of block nesting.  Actually, @code{pthread_cleanup_push} and
466 @code{pthread_cleanup_pop} are macros, and the expansion of
467 @code{pthread_cleanup_push} introduces an open brace @code{@{} with the
468 matching closing brace @code{@}} being introduced by the expansion of the
469 matching @code{pthread_cleanup_pop}.
471 @comment pthread.h
472 @comment GNU
473 @deftypefun void pthread_cleanup_push_defer_np (void (*@var{routine}) (void *), void *@var{arg})
474 @code{pthread_cleanup_push_defer_np} is a non-portable extension that
475 combines @code{pthread_cleanup_push} and @code{pthread_setcanceltype}.
476 It pushes a cleanup handler just as @code{pthread_cleanup_push} does,
477 but also saves the current cancellation type and sets it to deferred
478 cancellation. This ensures that the cleanup mechanism is effective even
479 if the thread was initially in asynchronous cancellation mode.
480 @end deftypefun
482 @comment pthread.h
483 @comment GNU
484 @deftypefun void pthread_cleanup_pop_restore_np (int @var{execute})
485 @code{pthread_cleanup_pop_restore_np} pops a cleanup handler introduced
486 by @code{pthread_cleanup_push_defer_np}, and restores the cancellation
487 type to its value at the time @code{pthread_cleanup_push_defer_np} was
488 called.
489 @end deftypefun
491 @code{pthread_cleanup_push_defer_np} and
492 @code{pthread_cleanup_pop_restore_np} must occur in matching pairs, at
493 the same level of block nesting.
495 The sequence
497 @smallexample
498 pthread_cleanup_push_defer_np(routine, arg);
500 pthread_cleanup_pop_defer_np(execute);
501 @end smallexample
503 @noindent
504 is functionally equivalent to (but more compact and efficient than)
506 @smallexample
508   int oldtype;
509   pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
510   pthread_cleanup_push(routine, arg);
511   ...
512   pthread_cleanup_pop(execute);
513   pthread_setcanceltype(oldtype, NULL);
515 @end smallexample
518 @node Mutexes
519 @section Mutexes
521 A mutex is a MUTual EXclusion device, and is useful for protecting
522 shared data structures from concurrent modifications, and implementing
523 critical sections and monitors.
525 A mutex has two possible states: unlocked (not owned by any thread),
526 and locked (owned by one thread). A mutex can never be owned by two
527 different threads simultaneously. A thread attempting to lock a mutex
528 that is already locked by another thread is suspended until the owning
529 thread unlocks the mutex first.
531 None of the mutex functions is a cancellation point, not even
532 @code{pthread_mutex_lock}, in spite of the fact that it can suspend a
533 thread for arbitrary durations. This way, the status of mutexes at
534 cancellation points is predictable, allowing cancellation handlers to
535 unlock precisely those mutexes that need to be unlocked before the
536 thread stops executing. Consequently, threads using deferred
537 cancellation should never hold a mutex for extended periods of time.
539 It is not safe to call mutex functions from a signal handler.  In
540 particular, calling @code{pthread_mutex_lock} or
541 @code{pthread_mutex_unlock} from a signal handler may deadlock the
542 calling thread.
544 @comment pthread.h
545 @comment POSIX
546 @deftypefun int pthread_mutex_init (pthread_mutex_t *@var{mutex}, const pthread_mutexattr_t *@var{mutexattr})
548 @code{pthread_mutex_init} initializes the mutex object pointed to by
549 @var{mutex} according to the mutex attributes specified in @var{mutexattr}.
550 If @var{mutexattr} is @code{NULL}, default attributes are used instead.
552 The LinuxThreads implementation supports only one mutex attribute,
553 the @var{mutex kind}, which is either ``fast'', ``recursive'', or
554 ``error checking''. The kind of a mutex determines whether
555 it can be locked again by a thread that already owns it.
556 The default kind is ``fast''.
558 Variables of type @code{pthread_mutex_t} can also be initialized
559 statically, using the constants @code{PTHREAD_MUTEX_INITIALIZER} (for
560 fast mutexes), @code{PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP} (for
561 recursive mutexes), and @code{PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP}
562 (for error checking mutexes).
564 @code{pthread_mutex_init} always returns 0.
565 @end deftypefun
567 @comment pthread.h
568 @comment POSIX
569 @deftypefun int pthread_mutex_lock (pthread_mutex_t *mutex))
570 @code{pthread_mutex_lock} locks the given mutex. If the mutex is
571 currently unlocked, it becomes locked and owned by the calling thread,
572 and @code{pthread_mutex_lock} returns immediately. If the mutex is
573 already locked by another thread, @code{pthread_mutex_lock} suspends the
574 calling thread until the mutex is unlocked.
576 If the mutex is already locked by the calling thread, the behavior of
577 @code{pthread_mutex_lock} depends on the kind of the mutex. If the mutex
578 is of the ``fast'' kind, the calling thread is suspended.  It will
579 remain suspended forever, because no other thread can unlock the mutex.
580 If  the mutex is of the ``error checking'' kind, @code{pthread_mutex_lock}
581 returns immediately with the error code @code{EDEADLK}.  If the mutex is
582 of the ``recursive'' kind, @code{pthread_mutex_lock} succeeds and
583 returns immediately, recording the number of times the calling thread
584 has locked the mutex. An equal number of @code{pthread_mutex_unlock}
585 operations must be performed before the mutex returns to the unlocked
586 state.
587 @end deftypefun
589 @comment pthread.h
590 @comment POSIX
591 @deftypefun int pthread_mutex_trylock (pthread_mutex_t *@var{mutex})
592 @code{pthread_mutex_trylock} behaves identically to
593 @code{pthread_mutex_lock}, except that it does not block the calling
594 thread if the mutex is already locked by another thread (or by the
595 calling thread in the case of a ``fast'' mutex). Instead,
596 @code{pthread_mutex_trylock} returns immediately with the error code
597 @code{EBUSY}.
598 @end deftypefun
600 @comment pthread.h
601 @comment POSIX
602 @deftypefun int pthread_mutex_timedlock (pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime})
603 The @code{pthread_mutex_timedlock} is similar to the
604 @code{pthread_mutex_lock} function but instead of blocking for in
605 indefinite time if the mutex is locked by another thread, it returns
606 when the time specified in @var{abstime} is reached.
608 This function can only be used on standard (``timed'') and ``error
609 checking'' mutexes.  It behaves just like @code{pthread_mutex_lock} for
610 all other types.
612 If the mutex is successfully locked, the function returns zero.  If the
613 time specified in @var{abstime} is reached without the mutex being locked,
614 @code{ETIMEDOUT} is returned.
616 This function was introduced in the POSIX.1d revision of the POSIX standard.
617 @end deftypefun
619 @comment pthread.h
620 @comment POSIX
621 @deftypefun int pthread_mutex_unlock (pthread_mutex_t *@var{mutex})
622 @code{pthread_mutex_unlock} unlocks the given mutex. The mutex is
623 assumed to be locked and owned by the calling thread on entrance to
624 @code{pthread_mutex_unlock}. If the mutex is of the ``fast'' kind,
625 @code{pthread_mutex_unlock} always returns it to the unlocked state. If
626 it is of the ``recursive'' kind, it decrements the locking count of the
627 mutex (number of @code{pthread_mutex_lock} operations performed on it by
628 the calling thread), and only when this count reaches zero is the mutex
629 actually unlocked.
631 On ``error checking'' mutexes, @code{pthread_mutex_unlock} actually
632 checks at run-time that the mutex is locked on entrance, and that it was
633 locked by the same thread that is now calling
634 @code{pthread_mutex_unlock}.  If these conditions are not met,
635 @code{pthread_mutex_unlock} returns @code{EPERM}, and the mutex remains
636 unchanged.  ``Fast'' and ``recursive'' mutexes perform no such checks,
637 thus allowing a locked mutex to be unlocked by a thread other than its
638 owner. This is non-portable behavior and must not be relied upon.
639 @end deftypefun
641 @comment pthread.h
642 @comment POSIX
643 @deftypefun int pthread_mutex_destroy (pthread_mutex_t *@var{mutex})
644 @code{pthread_mutex_destroy} destroys a mutex object, freeing the
645 resources it might hold. The mutex must be unlocked on entrance. In the
646 LinuxThreads implementation, no resources are associated with mutex
647 objects, thus @code{pthread_mutex_destroy} actually does nothing except
648 checking that the mutex is unlocked.
650 If the mutex is locked by some thread, @code{pthread_mutex_destroy}
651 returns @code{EBUSY}.  Otherwise it returns 0.
652 @end deftypefun
654 If any of the above functions (except @code{pthread_mutex_init})
655 is applied to an uninitialized mutex, they will simply return
656 @code{EINVAL} and do nothing.
658 A shared global variable @var{x} can be protected by a mutex as follows:
660 @smallexample
661 int x;
662 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
663 @end smallexample
665 All accesses and modifications to @var{x} should be bracketed by calls to
666 @code{pthread_mutex_lock} and @code{pthread_mutex_unlock} as follows:
668 @smallexample
669 pthread_mutex_lock(&mut);
670 /* operate on x */
671 pthread_mutex_unlock(&mut);
672 @end smallexample
674 Mutex attributes can be specified at mutex creation time, by passing a
675 mutex attribute object as second argument to @code{pthread_mutex_init}.
676 Passing @code{NULL} is equivalent to passing a mutex attribute object
677 with all attributes set to their default values.
679 @comment pthread.h
680 @comment POSIX
681 @deftypefun int pthread_mutexattr_init (pthread_mutexattr_t *@var{attr})
682 @code{pthread_mutexattr_init} initializes the mutex attribute object
683 @var{attr} and fills it with default values for the attributes.
685 This function always returns 0.
686 @end deftypefun
688 @comment pthread.h
689 @comment POSIX
690 @deftypefun int pthread_mutexattr_destroy (pthread_mutexattr_t *@var{attr})
691 @code{pthread_mutexattr_destroy} destroys a mutex attribute object,
692 which must not be reused until it is
693 reinitialized. @code{pthread_mutexattr_destroy} does nothing in the
694 LinuxThreads implementation.
696 This function always returns 0.
697 @end deftypefun
699 LinuxThreads supports only one mutex attribute: the mutex kind, which is
700 either @code{PTHREAD_MUTEX_FAST_NP} for ``fast'' mutexes,
701 @code{PTHREAD_MUTEX_RECURSIVE_NP} for ``recursive'' mutexes, or
702 @code{PTHREAD_MUTEX_ERRORCHECK_NP} for ``error checking'' mutexes.  As
703 the @code{NP} suffix indicates, this is a non-portable extension to the
704 POSIX standard and should not be employed in portable programs.
706 The mutex kind determines what happens if a thread attempts to lock a
707 mutex it already owns with @code{pthread_mutex_lock}. If the mutex is of
708 the ``fast'' kind, @code{pthread_mutex_lock} simply suspends the calling
709 thread forever.  If the mutex is of the ``error checking'' kind,
710 @code{pthread_mutex_lock} returns immediately with the error code
711 @code{EDEADLK}.  If the mutex is of the ``recursive'' kind, the call to
712 @code{pthread_mutex_lock} returns immediately with a success return
713 code. The number of times the thread owning the mutex has locked it is
714 recorded in the mutex. The owning thread must call
715 @code{pthread_mutex_unlock} the same number of times before the mutex
716 returns to the unlocked state.
718 The default mutex kind is ``fast'', that is, @code{PTHREAD_MUTEX_FAST_NP}.
720 @comment pthread.h
721 @comment GNU
722 @deftypefun int pthread_mutexattr_setkind_np (pthread_mutexattr_t *@var{attr}, int @var{kind})
723 @code{pthread_mutexattr_setkind_np} sets the mutex kind attribute in
724 @var{attr} to the value specified by @var{kind}.
726 If @var{kind} is not @code{PTHREAD_MUTEX_FAST_NP},
727 @code{PTHREAD_MUTEX_RECURSIVE_NP}, or
728 @code{PTHREAD_MUTEX_ERRORCHECK_NP}, this function will return
729 @code{EINVAL} and leave @var{attr} unchanged.
730 @end deftypefun
732 @comment pthread.h
733 @comment GNU
734 @deftypefun int pthread_mutexattr_getkind_np (const pthread_mutexattr_t *@var{attr}, int *@var{kind})
735 @code{pthread_mutexattr_getkind_np} retrieves the current value of the
736 mutex kind attribute in @var{attr} and stores it in the location pointed
737 to by @var{kind}.
739 This function always returns 0.
740 @end deftypefun
742 @node Condition Variables
743 @section Condition Variables
745 A condition (short for ``condition variable'') is a synchronization
746 device that allows threads to suspend execution until some predicate on
747 shared data is satisfied. The basic operations on conditions are: signal
748 the condition (when the predicate becomes true), and wait for the
749 condition, suspending the thread execution until another thread signals
750 the condition.
752 A condition variable must always be associated with a mutex, to avoid
753 the race condition where a thread prepares to wait on a condition
754 variable and another thread signals the condition just before the first
755 thread actually waits on it.
757 @comment pthread.h
758 @comment POSIX
759 @deftypefun int pthread_cond_init (pthread_cond_t *@var{cond}, pthread_condattr_t *cond_@var{attr})
761 @code{pthread_cond_init} initializes the condition variable @var{cond},
762 using the condition attributes specified in @var{cond_attr}, or default
763 attributes if @var{cond_attr} is @code{NULL}. The LinuxThreads
764 implementation supports no attributes for conditions, hence the
765 @var{cond_attr} parameter is actually ignored.
767 Variables of type @code{pthread_cond_t} can also be initialized
768 statically, using the constant @code{PTHREAD_COND_INITIALIZER}.
770 This function always returns 0.
771 @end deftypefun
773 @comment pthread.h
774 @comment POSIX
775 @deftypefun int pthread_cond_signal (pthread_cond_t *@var{cond})
776 @code{pthread_cond_signal} restarts one of the threads that are waiting
777 on the condition variable @var{cond}. If no threads are waiting on
778 @var{cond}, nothing happens. If several threads are waiting on
779 @var{cond}, exactly one is restarted, but it is not specified which.
781 This function always returns 0.
782 @end deftypefun
784 @comment pthread.h
785 @comment POSIX
786 @deftypefun int pthread_cond_broadcast (pthread_cond_t *@var{cond})
787 @code{pthread_cond_broadcast} restarts all the threads that are waiting
788 on the condition variable @var{cond}. Nothing happens if no threads are
789 waiting on @var{cond}.
791 This function always returns 0.
792 @end deftypefun
794 @comment pthread.h
795 @comment POSIX
796 @deftypefun int pthread_cond_wait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex})
797 @code{pthread_cond_wait} atomically unlocks the @var{mutex} (as per
798 @code{pthread_unlock_mutex}) and waits for the condition variable
799 @var{cond} to be signaled. The thread execution is suspended and does
800 not consume any CPU time until the condition variable is signaled. The
801 @var{mutex} must be locked by the calling thread on entrance to
802 @code{pthread_cond_wait}. Before returning to the calling thread,
803 @code{pthread_cond_wait} re-acquires @var{mutex} (as per
804 @code{pthread_lock_mutex}).
806 Unlocking the mutex and suspending on the condition variable is done
807 atomically. Thus, if all threads always acquire the mutex before
808 signaling the condition, this guarantees that the condition cannot be
809 signaled (and thus ignored) between the time a thread locks the mutex
810 and the time it waits on the condition variable.
812 This function always returns 0.
813 @end deftypefun
815 @comment pthread.h
816 @comment POSIX
817 @deftypefun int pthread_cond_timedwait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime})
818 @code{pthread_cond_timedwait} atomically unlocks @var{mutex} and waits
819 on @var{cond}, as @code{pthread_cond_wait} does, but it also bounds the
820 duration of the wait. If @var{cond} has not been signaled before time
821 @var{abstime}, the mutex @var{mutex} is re-acquired and
822 @code{pthread_cond_timedwait} returns the error code @code{ETIMEDOUT}.
823 The wait can also be interrupted by a signal; in that case
824 @code{pthread_cond_timedwait} returns @code{EINTR}.
826 The @var{abstime} parameter specifies an absolute time, with the same
827 origin as @code{time} and @code{gettimeofday}: an @var{abstime} of 0
828 corresponds to 00:00:00 GMT, January 1, 1970.
829 @end deftypefun
831 @comment pthread.h
832 @comment POSIX
833 @deftypefun int pthread_cond_destroy (pthread_cond_t *@var{cond})
834 @code{pthread_cond_destroy} destroys the condition variable @var{cond},
835 freeing the resources it might hold.  If any threads are waiting on the
836 condition variable, @code{pthread_cond_destroy} leaves @var{cond}
837 untouched and returns @code{EBUSY}.  Otherwise it returns 0, and
838 @var{cond} must not be used again until it is reinitialized.
840 In the LinuxThreads implementation, no resources are associated with
841 condition variables, so @code{pthread_cond_destroy} actually does
842 nothing.
843 @end deftypefun
845 @code{pthread_cond_wait} and @code{pthread_cond_timedwait} are
846 cancellation points. If a thread is cancelled while suspended in one of
847 these functions, the thread immediately resumes execution, relocks the
848 mutex specified by  @var{mutex}, and finally executes the cancellation.
849 Consequently, cleanup handlers are assured that @var{mutex} is locked
850 when they are called.
852 It is not safe to call the condition variable functions from a signal
853 handler. In particular, calling @code{pthread_cond_signal} or
854 @code{pthread_cond_broadcast} from a signal handler may deadlock the
855 calling thread.
857 Consider two shared variables @var{x} and @var{y}, protected by the
858 mutex @var{mut}, and a condition variable @var{cond} that is to be
859 signaled whenever @var{x} becomes greater than @var{y}.
861 @smallexample
862 int x,y;
863 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
864 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
865 @end smallexample
867 Waiting until @var{x} is greater than @var{y} is performed as follows:
869 @smallexample
870 pthread_mutex_lock(&mut);
871 while (x <= y) @{
872         pthread_cond_wait(&cond, &mut);
874 /* operate on x and y */
875 pthread_mutex_unlock(&mut);
876 @end smallexample
878 Modifications on @var{x} and @var{y} that may cause @var{x} to become greater than
879 @var{y} should signal the condition if needed:
881 @smallexample
882 pthread_mutex_lock(&mut);
883 /* modify x and y */
884 if (x > y) pthread_cond_broadcast(&cond);
885 pthread_mutex_unlock(&mut);
886 @end smallexample
888 If it can be proved that at most one waiting thread needs to be waken
889 up (for instance, if there are only two threads communicating through
890 @var{x} and @var{y}), @code{pthread_cond_signal} can be used as a slightly more
891 efficient alternative to @code{pthread_cond_broadcast}. In doubt, use
892 @code{pthread_cond_broadcast}.
894 To wait for @var{x} to becomes greater than @var{y} with a timeout of 5
895 seconds, do:
897 @smallexample
898 struct timeval now;
899 struct timespec timeout;
900 int retcode;
902 pthread_mutex_lock(&mut);
903 gettimeofday(&now);
904 timeout.tv_sec = now.tv_sec + 5;
905 timeout.tv_nsec = now.tv_usec * 1000;
906 retcode = 0;
907 while (x <= y && retcode != ETIMEDOUT) @{
908         retcode = pthread_cond_timedwait(&cond, &mut, &timeout);
910 if (retcode == ETIMEDOUT) @{
911         /* timeout occurred */
912 @} else @{
913         /* operate on x and y */
915 pthread_mutex_unlock(&mut);
916 @end smallexample
918 Condition attributes can be specified at condition creation time, by
919 passing a condition attribute object as second argument to
920 @code{pthread_cond_init}.  Passing @code{NULL} is equivalent to passing
921 a condition attribute object with all attributes set to their default
922 values.
924 The LinuxThreads implementation supports no attributes for
925 conditions. The functions on condition attributes are included only for
926 compliance with the POSIX standard.
928 @comment pthread.h
929 @comment POSIX
930 @deftypefun int pthread_condattr_init (pthread_condattr_t *@var{attr})
931 @deftypefunx int pthread_condattr_destroy (pthread_condattr_t *@var{attr})
932 @code{pthread_condattr_init} initializes the condition attribute object
933 @var{attr} and fills it with default values for the attributes.
934 @code{pthread_condattr_destroy} destroys the condition attribute object
935 @var{attr}.
937 Both functions do nothing in the LinuxThreads implementation.
939 @code{pthread_condattr_init} and @code{pthread_condattr_destroy} always
940 return 0.
941 @end deftypefun
943 @node POSIX Semaphores
944 @section POSIX Semaphores
946 @vindex SEM_VALUE_MAX
947 Semaphores are counters for resources shared between threads. The
948 basic operations on semaphores are: increment the counter atomically,
949 and wait until the counter is non-null and decrement it atomically.
951 Semaphores have a maximum value past which they cannot be incremented.
952 The macro @code{SEM_VALUE_MAX} is defined to be this maximum value.  In
953 the GNU C library, @code{SEM_VALUE_MAX} is equal to @code{INT_MAX}
954 (@pxref{Range of Type}), but it may be much smaller on other systems.
956 The pthreads library implements POSIX 1003.1b semaphores.  These should
957 not be confused with System V semaphores (@code{ipc}, @code{semctl} and
958 @code{semop}).
959 @c !!! SysV IPC is not doc'd at all in our manual
961 All the semaphore functions and macros are defined in @file{semaphore.h}.
963 @comment semaphore.h
964 @comment POSIX
965 @deftypefun int sem_init (sem_t *@var{sem}, int @var{pshared}, unsigned int @var{value})
966 @code{sem_init} initializes the semaphore object pointed to by
967 @var{sem}. The count associated with the semaphore is set initially to
968 @var{value}. The @var{pshared} argument indicates whether the semaphore
969 is local to the current process (@var{pshared} is zero) or is to be
970 shared between several processes (@var{pshared} is not zero).
972 On success @code{sem_init} returns 0.  On failure it returns -1 and sets
973 @var{errno} to one of the following values:
975 @table @code
976 @item EINVAL
977 @var{value} exceeds the maximal counter value @code{SEM_VALUE_MAX}
979 @item ENOSYS
980 @var{pshared} is not zero.  LinuxThreads currently does not support
981 process-shared semaphores.  (This will eventually change.)
982 @end table
983 @end deftypefun
985 @comment semaphore.h
986 @comment POSIX
987 @deftypefun int sem_destroy (sem_t * @var{sem})
988 @code{sem_destroy} destroys a semaphore object, freeing the resources it
989 might hold.  If any threads are waiting on the semaphore when
990 @code{sem_destroy} is called, it fails and sets @var{errno} to
991 @code{EBUSY}.
993 In the LinuxThreads implementation, no resources are associated with
994 semaphore objects, thus @code{sem_destroy} actually does nothing except
995 checking that no thread is waiting on the semaphore.  This will change
996 when process-shared semaphores are implemented.
997 @end deftypefun
999 @comment semaphore.h
1000 @comment POSIX
1001 @deftypefun int sem_wait (sem_t * @var{sem})
1002 @code{sem_wait} suspends the calling thread until the semaphore pointed
1003 to by @var{sem} has non-zero count. It then atomically decreases the
1004 semaphore count.
1006 @code{sem_wait} is a cancellation point.  It always returns 0.
1007 @end deftypefun
1009 @comment semaphore.h
1010 @comment POSIX
1011 @deftypefun int sem_trywait (sem_t * @var{sem})
1012 @code{sem_trywait} is a non-blocking variant of @code{sem_wait}. If the
1013 semaphore pointed to by @var{sem} has non-zero count, the count is
1014 atomically decreased and @code{sem_trywait} immediately returns 0.  If
1015 the semaphore count is zero, @code{sem_trywait} immediately returns -1
1016 and sets errno to @code{EAGAIN}.
1017 @end deftypefun
1019 @comment semaphore.h
1020 @comment POSIX
1021 @deftypefun int sem_post (sem_t * @var{sem})
1022 @code{sem_post} atomically increases the count of the semaphore pointed to
1023 by @var{sem}. This function never blocks.
1025 @c !!! This para appears not to agree with the code.
1026 On processors supporting atomic compare-and-swap (Intel 486, Pentium and
1027 later, Alpha, PowerPC, MIPS II, Motorola 68k, Ultrasparc), the
1028 @code{sem_post} function is can safely be called from signal handlers.
1029 This is the only thread synchronization function provided by POSIX
1030 threads that is async-signal safe.  On the Intel 386 and earlier Sparc
1031 chips, the current LinuxThreads implementation of @code{sem_post} is not
1032 async-signal safe, because the hardware does not support the required
1033 atomic operations.
1035 @code{sem_post} always succeeds and returns 0, unless the semaphore
1036 count would exceed @code{SEM_VALUE_MAX} after being incremented.  In
1037 that case @code{sem_post} returns -1 and sets @var{errno} to
1038 @code{EINVAL}.  The semaphore count is left unchanged.
1039 @end deftypefun
1041 @comment semaphore.h
1042 @comment POSIX
1043 @deftypefun int sem_getvalue (sem_t * @var{sem}, int * @var{sval})
1044 @code{sem_getvalue} stores in the location pointed to by @var{sval} the
1045 current count of the semaphore @var{sem}.  It always returns 0.
1046 @end deftypefun
1048 @node Thread-Specific Data
1049 @section Thread-Specific Data
1051 Programs often need global or static variables that have different
1052 values in different threads. Since threads share one memory space, this
1053 cannot be achieved with regular variables. Thread-specific data is the
1054 POSIX threads answer to this need.
1056 Each thread possesses a private memory block, the thread-specific data
1057 area, or TSD area for short. This area is indexed by TSD keys. The TSD
1058 area associates values of type @code{void *} to TSD keys. TSD keys are
1059 common to all threads, but the value associated with a given TSD key can
1060 be different in each thread.
1062 For concreteness, the TSD areas can be viewed as arrays of @code{void *}
1063 pointers, TSD keys as integer indices into these arrays, and the value
1064 of a TSD key as the value of the corresponding array element in the
1065 calling thread.
1067 When a thread is created, its TSD area initially associates @code{NULL}
1068 with all keys.
1070 @comment pthread.h
1071 @comment POSIX
1072 @deftypefun int pthread_key_create (pthread_key_t *@var{key}, void (*destr_function) (void *))
1073 @code{pthread_key_create} allocates a new TSD key. The key is stored in
1074 the location pointed to by @var{key}. There is a limit of
1075 @code{PTHREAD_KEYS_MAX} on the number of keys allocated at a given
1076 time. The value initially associated with the returned key is
1077 @code{NULL} in all currently executing threads.
1079 The @var{destr_function} argument, if not @code{NULL}, specifies a
1080 destructor function associated with the key. When a thread terminates
1081 via @code{pthread_exit} or by cancellation, @var{destr_function} is
1082 called on the value associated with the key in that thread. The
1083 @var{destr_function} is not called if a key is deleted with
1084 @code{pthread_key_delete} or a value is changed with
1085 @code{pthread_setspecific}.  The order in which destructor functions are
1086 called at thread termination time is unspecified.
1088 Before the destructor function is called, the @code{NULL} value is
1089 associated with the key in the current thread.  A destructor function
1090 might, however, re-associate non-@code{NULL} values to that key or some
1091 other key.  To deal with this, if after all the destructors have been
1092 called for all non-@code{NULL} values, there are still some
1093 non-@code{NULL} values with associated destructors, then the process is
1094 repeated.  The LinuxThreads implementation stops the process after
1095 @code{PTHREAD_DESTRUCTOR_ITERATIONS} iterations, even if some
1096 non-@code{NULL} values with associated descriptors remain.  Other
1097 implementations may loop indefinitely.
1099 @code{pthread_key_create} returns 0 unless @code{PTHREAD_KEYS_MAX} keys
1100 have already been allocated, in which case it fails and returns
1101 @code{EAGAIN}.
1102 @end deftypefun
1105 @comment pthread.h
1106 @comment POSIX
1107 @deftypefun int pthread_key_delete (pthread_key_t @var{key})
1108 @code{pthread_key_delete} deallocates a TSD key. It does not check
1109 whether non-@code{NULL} values are associated with that key in the
1110 currently executing threads, nor call the destructor function associated
1111 with the key.
1113 If there is no such key @var{key}, it returns @code{EINVAL}.  Otherwise
1114 it returns 0.
1115 @end deftypefun
1117 @comment pthread.h
1118 @comment POSIX
1119 @deftypefun int pthread_setspecific (pthread_key_t @var{key}, const void *@var{pointer})
1120 @code{pthread_setspecific} changes the value associated with @var{key}
1121 in the calling thread, storing the given @var{pointer} instead.
1123 If there is no such key @var{key}, it returns @code{EINVAL}.  Otherwise
1124 it returns 0.
1125 @end deftypefun
1127 @comment pthread.h
1128 @comment POSIX
1129 @deftypefun {void *} pthread_getspecific (pthread_key_t @var{key})
1130 @code{pthread_getspecific} returns the value currently associated with
1131 @var{key} in the calling thread.
1133 If there is no such key @var{key}, it returns @code{NULL}.
1134 @end deftypefun
1136 The following code fragment allocates a thread-specific array of 100
1137 characters, with automatic reclaimation at thread exit:
1139 @smallexample
1140 /* Key for the thread-specific buffer */
1141 static pthread_key_t buffer_key;
1143 /* Once-only initialisation of the key */
1144 static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
1146 /* Allocate the thread-specific buffer */
1147 void buffer_alloc(void)
1149   pthread_once(&buffer_key_once, buffer_key_alloc);
1150   pthread_setspecific(buffer_key, malloc(100));
1153 /* Return the thread-specific buffer */
1154 char * get_buffer(void)
1156   return (char *) pthread_getspecific(buffer_key);
1159 /* Allocate the key */
1160 static void buffer_key_alloc()
1162   pthread_key_create(&buffer_key, buffer_destroy);
1165 /* Free the thread-specific buffer */
1166 static void buffer_destroy(void * buf)
1168   free(buf);
1170 @end smallexample
1172 @node Threads and Signal Handling
1173 @section Threads and Signal Handling
1175 @comment pthread.h
1176 @comment POSIX
1177 @deftypefun int pthread_sigmask (int @var{how}, const sigset_t *@var{newmask}, sigset_t *@var{oldmask})
1178 @code{pthread_sigmask} changes the signal mask for the calling thread as
1179 described by the @var{how} and @var{newmask} arguments. If @var{oldmask}
1180 is not @code{NULL}, the previous signal mask is stored in the location
1181 pointed to by @var{oldmask}.
1183 The meaning of the @var{how} and @var{newmask} arguments is the same as
1184 for @code{sigprocmask}. If @var{how} is @code{SIG_SETMASK}, the signal
1185 mask is set to @var{newmask}. If @var{how} is @code{SIG_BLOCK}, the
1186 signals specified to @var{newmask} are added to the current signal mask.
1187 If @var{how} is @code{SIG_UNBLOCK}, the signals specified to
1188 @var{newmask} are removed from the current signal mask.
1190 Recall that signal masks are set on a per-thread basis, but signal
1191 actions and signal handlers, as set with @code{sigaction}, are shared
1192 between all threads.
1194 The @code{pthread_sigmask} function returns 0 on success, and one of the
1195 following error codes on error:
1196 @table @code
1197 @item EINVAL
1198 @var{how} is not one of @code{SIG_SETMASK}, @code{SIG_BLOCK}, or @code{SIG_UNBLOCK}
1200 @item EFAULT
1201 @var{newmask} or @var{oldmask} point to invalid addresses
1202 @end table
1203 @end deftypefun
1205 @comment pthread.h
1206 @comment POSIX
1207 @deftypefun int pthread_kill (pthread_t @var{thread}, int @var{signo})
1208 @code{pthread_kill} sends signal number @var{signo} to the thread
1209 @var{thread}.  The signal is delivered and handled as described in
1210 @ref{Signal Handling}.
1212 @code{pthread_kill} returns 0 on success, one of the following error codes
1213 on error:
1214 @table @code
1215 @item EINVAL
1216 @var{signo} is not a valid signal number
1218 @item ESRCH
1219 The thread @var{thread} does not exist (e.g. it has already terminated)
1220 @end table
1221 @end deftypefun
1223 @comment pthread.h
1224 @comment POSIX
1225 @deftypefun int sigwait (const sigset_t *@var{set}, int *@var{sig})
1226 @code{sigwait} suspends the calling thread until one of the signals in
1227 @var{set} is delivered to the calling thread. It then stores the number
1228 of the signal received in the location pointed to by @var{sig} and
1229 returns. The signals in @var{set} must be blocked and not ignored on
1230 entrance to @code{sigwait}. If the delivered signal has a signal handler
1231 function attached, that function is @emph{not} called.
1233 @code{sigwait} is a cancellation point.  It always returns 0.
1234 @end deftypefun
1236 For @code{sigwait} to work reliably, the signals being waited for must be
1237 blocked in all threads, not only in the calling thread, since
1238 otherwise the POSIX semantics for signal delivery do not guarantee
1239 that it's the thread doing the @code{sigwait} that will receive the signal.
1240 The best way to achieve this is block those signals before any threads
1241 are created, and never unblock them in the program other than by
1242 calling @code{sigwait}.
1244 Signal handling in LinuxThreads departs significantly from the POSIX
1245 standard. According to the standard, ``asynchronous'' (external) signals
1246 are addressed to the whole process (the collection of all threads),
1247 which then delivers them to one particular thread. The thread that
1248 actually receives the signal is any thread that does not currently block
1249 the signal.
1251 In LinuxThreads, each thread is actually a kernel process with its own
1252 PID, so external signals are always directed to one particular thread.
1253 If, for instance, another thread is blocked in @code{sigwait} on that
1254 signal, it will not be restarted.
1256 The LinuxThreads implementation of @code{sigwait} installs dummy signal
1257 handlers for the signals in @var{set} for the duration of the
1258 wait. Since signal handlers are shared between all threads, other
1259 threads must not attach their own signal handlers to these signals, or
1260 alternatively they should all block these signals (which is recommended
1261 anyway).
1263 @node Threads and Fork
1264 @section Threads and Fork
1266 It's not intuitively obvious what should happen when a multi-threaded POSIX
1267 process calls @code{fork}. Not only are the semantics tricky, but you may
1268 need to write code that does the right thing at fork time even if that code
1269 doesn't use the @code{fork} function. Moreover, you need to be aware of
1270 interaction between @code{fork} and some library features like
1271 @code{pthread_once} and stdio streams.
1273 When @code{fork} is called by one of the threads of a process, it creates a new
1274 process which is copy of the  calling process. Effectively, in addition to
1275 copying certain system objects, the function takes a snapshot of the memory
1276 areas of the parent process, and creates identical areas in the child.
1277 To make matters more complicated, with threads it's possible for two or more
1278 threads to concurrently call fork to create two or more child processes.
1280 The child process has a copy of the address space of the parent, but it does
1281 not inherit any of its threads. Execution of the child process is carried out
1282 by a new thread which returns from @code{fork} function with a return value of
1283 zero; it is the only thread in the child process.  Because threads are not
1284 inherited across fork, issues arise. At the time of the call to @code{fork},
1285 threads in the parent process other than the one calling @code{fork} may have
1286 been executing critical regions of code.  As a result, the child process may
1287 get a copy of objects that are not in a well-defined state.  This potential
1288 problem affects all components of the program.
1290 Any program component which will continue being used in a child process must
1291 correctly handle its state during @code{fork}. For this purpose, the POSIX
1292 interface provides the special function @code{pthread_atfork} for installing
1293 pointers to handler functions which are called from within @code{fork}.
1295 @comment pthread.h
1296 @comment POSIX
1297 @deftypefun int pthread_atfork (void (*@var{prepare})(void), void (*@var{parent})(void), void (*@var{child})(void))
1299 @code{pthread_atfork} registers handler functions to be called just
1300 before and just after a new process is created with @code{fork}. The
1301 @var{prepare} handler will be called from the parent process, just
1302 before the new process is created. The @var{parent} handler will be
1303 called from the parent process, just before @code{fork} returns. The
1304 @var{child} handler will be called from the child process, just before
1305 @code{fork} returns.
1307 @code{pthread_atfork} returns 0 on success and a non-zero error code on
1308 error.
1310 One or more of the three handlers @var{prepare}, @var{parent} and
1311 @var{child} can be given as @code{NULL}, meaning that no handler needs
1312 to be called at the corresponding point.
1314 @code{pthread_atfork} can be called several times to install several
1315 sets of handlers. At @code{fork} time, the @var{prepare} handlers are
1316 called in LIFO order (last added with @code{pthread_atfork}, first
1317 called before @code{fork}), while the @var{parent} and @var{child}
1318 handlers are called in FIFO order (first added, first called).
1320 If there is insufficient memory available to register the handlers,
1321 @code{pthread_atfork} fails and returns @code{ENOMEM}.  Otherwise it
1322 returns 0.
1324 The functions @code{fork} and @code{pthread_atfork} must not be regarded as
1325 reentrant from the context of the handlers.  That is to say, if a
1326 @code{pthread_atfork} handler invoked from within @code{fork} calls
1327 @code{pthread_atfork} or @code{fork}, the behavior is undefined.
1329 Registering a triplet of handlers is an atomic operation with respect to fork.
1330 If new handlers are registered at about the same time as a fork occurs, either
1331 all three handlers will be called, or none of them will be called.
1333 The handlers are inherited by the child process, and there is no
1334 way to remove them, short of using @code{exec} to load a new
1335 pocess image.
1337 @end deftypefun
1339 To understand the purpose of @code{pthread_atfork}, recall that
1340 @code{fork} duplicates the whole memory space, including mutexes in
1341 their current locking state, but only the calling thread: other threads
1342 are not running in the child process. Thus, if a mutex is locked by a
1343 thread other than the thread calling @code{fork}, that mutex will remain
1344 locked forever in the child process, possibly blocking the execution of
1345 the child process. Or if some shared data, such as a linked list, was in the
1346 middle of being updated by a thread in the parent process, the child
1347 will get a copy of the incompletely updated data which it cannot use.
1349 To avoid this, install handlers with @code{pthread_atfork} as follows: have the
1350 @var{prepare} handler lock the mutexes (in locking order), and the
1351 @var{parent} handler unlock the mutexes. The @var{child} handler should reset
1352 the mutexes using @code{pthread_mutex_init}, as well as any other
1353 synchronization objects such as condition variables.
1355 Locking the global mutexes before the fork ensures that all other threads are
1356 locked out of the critical regions of code protected by those mutexes.  Thus
1357 when @code{fork} takes a snapshot of the parent's address space, that snapshot
1358 will copy valid, stable data.  Resetting the synchronization objects in the
1359 child process will ensure they are properly cleansed of any artifacts from the
1360 threading subsystem of the parent process. For example, a mutex may inherit
1361 a wait queue of threads waiting for the lock; this wait queue makes no sense
1362 in the child process. Initializing the mutex takes care of this.
1364 @node Streams and Fork
1365 @section Streams and Fork
1367 The GNU standard I/O library has an internal mutex which guards the internal
1368 linked list of all standard C FILE objects. This mutex is properly taken care
1369 of during @code{fork} so that the child receives an intact copy of the list.
1370 This allows the @code{fopen} function, and related stream-creating functions,
1371 to work correctly in the child process, since these functions need to insert
1372 into the list.
1374 However, the individual stream locks are not completely taken care of.  Thus
1375 unless the multithreaded application takes special precautions in its use of
1376 @code{fork}, the child process might not be able to safely use the streams that
1377 it inherited from the parent.   In general, for any given open stream in the
1378 parent that is to be used by the child process, the application must ensure
1379 that that stream is not in use by another thread when @code{fork} is called.
1380 Otherwise an inconsistent copy of the stream object be produced. An easy way to
1381 ensure this is to use @code{flockfile} to lock the stream prior to calling
1382 @code{fork} and then unlock it with @code{funlockfile} inside the parent
1383 process, provided that the parent's threads properly honor these locks.
1384 Nothing special needs to be done in the child process, since the library
1385 internally resets all stream locks.
1387 Note that the stream locks are not shared between the parent and child.
1388 For example, even if you ensure that, say, the stream @code{stdout} is properly
1389 treated and can be safely used in the child, the stream locks do not provide
1390 an exclusion mechanism between the parent and child. If both processes write
1391 to @code{stdout}, strangely interleaved output may result regardless of
1392 the explicit use of @code{flockfile} or implicit locks.
1394 Also note that these provisions are a GNU extension; other systems might not
1395 provide any way for streams to be used in the child of a multithreaded process.
1396 POSIX requires that such a child process confines itself to calling only
1397 asynchronous safe functions, which excludes much of the library, including
1398 standard I/O.
1400 @node Miscellaneous Thread Functions
1401 @section Miscellaneous Thread Functions
1403 @comment pthread.h
1404 @comment POSIX
1405 @deftypefun {pthread_t} pthread_self (@var{void})
1406 @code{pthread_self} returns the thread identifier for the calling thread.
1407 @end deftypefun
1409 @comment pthread.h
1410 @comment POSIX
1411 @deftypefun int pthread_equal (pthread_t thread1, pthread_t thread2)
1412 @code{pthread_equal} determines if two thread identifiers refer to the same
1413 thread.
1415 A non-zero value is returned if @var{thread1} and @var{thread2} refer to
1416 the same thread. Otherwise, 0 is returned.
1417 @end deftypefun
1419 @comment pthread.h
1420 @comment POSIX
1421 @deftypefun int pthread_detach (pthread_t @var{th})
1422 @code{pthread_detach} puts the thread @var{th} in the detached
1423 state. This guarantees that the memory resources consumed by @var{th}
1424 will be freed immediately when @var{th} terminates. However, this
1425 prevents other threads from synchronizing on the termination of @var{th}
1426 using @code{pthread_join}.
1428 A thread can be created initially in the detached state, using the
1429 @code{detachstate} attribute to @code{pthread_create}. In contrast,
1430 @code{pthread_detach} applies to threads created in the joinable state,
1431 and which need to be put in the detached state later.
1433 After @code{pthread_detach} completes, subsequent attempts to perform
1434 @code{pthread_join} on @var{th} will fail. If another thread is already
1435 joining the thread @var{th} at the time @code{pthread_detach} is called,
1436 @code{pthread_detach} does nothing and leaves @var{th} in the joinable
1437 state.
1439 On success, 0 is returned. On error, one of the following codes is
1440 returned:
1441 @table @code
1442 @item ESRCH
1443 No thread could be found corresponding to that specified by @var{th}
1444 @item EINVAL
1445 The thread @var{th} is already in the detached state
1446 @end table
1447 @end deftypefun
1449 @comment pthread.h
1450 @comment GNU
1451 @deftypefun void pthread_kill_other_threads_np (@var{void})
1452 @code{pthread_kill_other_threads_np} is a non-portable LinuxThreads extension.
1453 It causes all threads in the program to terminate immediately, except
1454 the calling thread which proceeds normally. It is intended to be
1455 called just before a thread calls one of the @code{exec} functions,
1456 e.g. @code{execve}.
1458 Termination of the other threads is not performed through
1459 @code{pthread_cancel} and completely bypasses the cancellation
1460 mechanism. Hence, the current settings for cancellation state and
1461 cancellation type are ignored, and the cleanup handlers are not
1462 executed in the terminated threads.
1464 According to POSIX 1003.1c, a successful @code{exec*} in one of the
1465 threads should automatically terminate all other threads in the program.
1466 This behavior is not yet implemented in LinuxThreads.  Calling
1467 @code{pthread_kill_other_threads_np} before @code{exec*} achieves much
1468 of the same behavior, except that if @code{exec*} ultimately fails, then
1469 all other threads are already killed.
1470 @end deftypefun
1472 @comment pthread.h
1473 @comment POSIX
1474 @deftypefun int pthread_once (pthread_once_t *once_@var{control}, void (*@var{init_routine}) (void))
1476 The purpose of @code{pthread_once} is to ensure that a piece of
1477 initialization code is executed at most once. The @var{once_control}
1478 argument points to a static or extern variable statically initialized
1479 to @code{PTHREAD_ONCE_INIT}.
1481 The first time @code{pthread_once} is called with a given
1482 @var{once_control} argument, it calls @var{init_routine} with no
1483 argument and changes the value of the @var{once_control} variable to
1484 record that initialization has been performed. Subsequent calls to
1485 @code{pthread_once} with the same @code{once_control} argument do
1486 nothing.
1488 If a thread is cancelled while executing @var{init_routine}
1489 the state of the @var{once_control} variable is reset so that
1490 a future call to @code{pthread_once} will call the routine again.
1492 If the process forks while one or more threads are executing
1493 @code{pthread_once} initialization routines, the states of their respective
1494 @var{once_control} variables will appear to be reset in the child process so
1495 that if the child calls @code{pthread_once}, the routines will be executed.
1497 @code{pthread_once} always returns 0.
1498 @end deftypefun
1500 @comment pthread.h
1501 @comment POSIX
1502 @deftypefun int pthread_setschedparam (pthread_t target_@var{thread}, int @var{policy}, const struct sched_param *@var{param})
1504 @code{pthread_setschedparam} sets the scheduling parameters for the
1505 thread @var{target_thread} as indicated by @var{policy} and
1506 @var{param}. @var{policy} can be either @code{SCHED_OTHER} (regular,
1507 non-realtime scheduling), @code{SCHED_RR} (realtime, round-robin) or
1508 @code{SCHED_FIFO} (realtime, first-in first-out). @var{param} specifies
1509 the scheduling priority for the two realtime policies.  See
1510 @code{sched_setpolicy} for more information on scheduling policies.
1512 The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
1513 are available only to processes with superuser privileges.
1515 On success, @code{pthread_setschedparam} returns 0.  On error it returns
1516 one of the following codes:
1517 @table @code
1518 @item EINVAL
1519 @var{policy} is not one of @code{SCHED_OTHER}, @code{SCHED_RR},
1520 @code{SCHED_FIFO}, or the priority value specified by @var{param} is not
1521 valid for the specified policy
1523 @item EPERM
1524 Realtime scheduling was requested but the calling process does not have
1525 sufficient privileges.
1527 @item ESRCH
1528 The @var{target_thread} is invalid or has already terminated
1530 @item EFAULT
1531 @var{param} points outside the process memory space
1532 @end table
1533 @end deftypefun
1535 @comment pthread.h
1536 @comment POSIX
1537 @deftypefun int pthread_getschedparam (pthread_t target_@var{thread}, int *@var{policy}, struct sched_param *@var{param})
1539 @code{pthread_getschedparam} retrieves the scheduling policy and
1540 scheduling parameters for the thread @var{target_thread} and stores them
1541 in the locations pointed to by @var{policy} and @var{param},
1542 respectively.
1544 @code{pthread_getschedparam} returns 0 on success, or one of the
1545 following error codes on failure:
1546 @table @code
1547 @item ESRCH
1548 The @var{target_thread} is invalid or has already terminated.
1550 @item EFAULT
1551 @var{policy} or @var{param} point outside the process memory space.
1553 @end table
1554 @end deftypefun