1 @node POSIX Threads, , Top, Top
3 @c %MENU% The standard threads library
5 @c This chapter needs more work bigtime. -zw
7 This chapter describes the pthreads (POSIX threads) library. This
8 library provides support functions for multithreaded programs: thread
9 primitives, synchronization objects, and so forth. It also implements
10 POSIX 1003.1b semaphores (not to be confused with System V semaphores).
12 The threads operations (@samp{pthread_*}) do not use @var{errno}.
13 Instead they return an error code directly. The semaphore operations do
17 * Basic Thread Operations:: Creating, terminating, and waiting for threads.
18 * Thread Attributes:: Tuning thread scheduling.
19 * Cancellation:: Stopping a thread before it's done.
20 * Cleanup Handlers:: Deallocating resources when a thread is
22 * Mutexes:: One way to synchronize threads.
23 * Condition Variables:: Another way.
24 * POSIX Semaphores:: And a third way.
25 * Thread-Specific Data:: Variables with different values in
27 * Threads and Signal Handling:: Why you should avoid mixing the two, and
28 how to do it if you must.
29 * Miscellaneous Thread Functions:: A grab bag of utility routines.
32 @node Basic Thread Operations
33 @section Basic Thread Operations
35 These functions are the thread equivalents of @code{fork}, @code{exit},
40 @deftypefun int pthread_create (pthread_t * @var{thread}, pthread_attr_t * @var{attr}, void * (*@var{start_routine})(void *), void * @var{arg})
41 @code{pthread_create} creates a new thread of control that executes
42 concurrently with the calling thread. The new thread calls the
43 function @var{start_routine}, passing it @var{arg} as first argument. The
44 new thread terminates either explicitly, by calling @code{pthread_exit},
45 or implicitly, by returning from the @var{start_routine} function. The
46 latter case is equivalent to calling @code{pthread_exit} with the result
47 returned by @var{start_routine} as exit code.
49 The @var{attr} argument specifies thread attributes to be applied to the
50 new thread. @xref{Thread Attributes} for details. The @var{attr}
51 argument can also be @code{NULL}, in which case default attributes are
52 used: the created thread is joinable (not detached) and has an ordinary
53 (not realtime) scheduling policy.
55 On success, the identifier of the newly created thread is stored in the
56 location pointed by the @var{thread} argument, and a 0 is returned. On
57 error, a non-zero error code is returned.
59 This function may return the following errors:
62 Not enough system resources to create a process for the new thread,
63 or more than @code{PTHREAD_THREADS_MAX} threads are already active.
69 @deftypefun void pthread_exit (void *@var{retval})
70 @code{pthread_exit} terminates the execution of the calling thread. All
71 cleanup handlers (@pxref{Cleanup Handlers}) that have been set for the
72 calling thread with @code{pthread_cleanup_push} are executed in reverse
73 order (the most recently pushed handler is executed first). Finalization
74 functions for thread-specific data are then called for all keys that
75 have non-@code{NULL} values associated with them in the calling thread
76 (@pxref{Thread-Specific Data}). Finally, execution of the calling
79 The @var{retval} argument is the return value of the thread. It can be
80 retrieved from another thread using @code{pthread_join}.
82 The @code{pthread_exit} function never returns.
87 @deftypefun int pthread_cancel (pthread_t @var{thread})
89 @code{pthread_cancel} sends a cancellation request to the thread denoted
90 by the @var{thread} argument. If there is no such thread,
91 @code{pthread_cancel} fails and returns @code{ESRCH}. Otherwise it
92 returns 0. @xref{Cancellation}, for details.
97 @deftypefun int pthread_join (pthread_t @var{th}, void **thread_@var{return})
98 @code{pthread_join} suspends the execution of the calling thread until
99 the thread identified by @var{th} terminates, either by calling
100 @code{pthread_exit} or by being cancelled.
102 If @var{thread_return} is not @code{NULL}, the return value of @var{th}
103 is stored in the location pointed to by @var{thread_return}. The return
104 value of @var{th} is either the argument it gave to @code{pthread_exit},
105 or @code{PTHREAD_CANCELED} if @var{th} was cancelled.
107 The joined thread @code{th} must be in the joinable state: it must not
108 have been detached using @code{pthread_detach} or the
109 @code{PTHREAD_CREATE_DETACHED} attribute to @code{pthread_create}.
111 When a joinable thread terminates, its memory resources (thread
112 descriptor and stack) are not deallocated until another thread performs
113 @code{pthread_join} on it. Therefore, @code{pthread_join} must be called
114 once for each joinable thread created to avoid memory leaks.
116 At most one thread can wait for the termination of a given
117 thread. Calling @code{pthread_join} on a thread @var{th} on which
118 another thread is already waiting for termination returns an error.
120 @code{pthread_join} is a cancellation point. If a thread is canceled
121 while suspended in @code{pthread_join}, the thread execution resumes
122 immediately and the cancellation is executed without waiting for the
123 @var{th} thread to terminate. If cancellation occurs during
124 @code{pthread_join}, the @var{th} thread remains not joined.
126 On success, the return value of @var{th} is stored in the location
127 pointed to by @var{thread_return}, and 0 is returned. On error, one of
128 the following values is returned:
131 No thread could be found corresponding to that specified by @var{th}.
133 The @var{th} thread has been detached, or another thread is already
134 waiting on termination of @var{th}.
136 The @var{th} argument refers to the calling thread.
140 @node Thread Attributes
141 @section Thread Attributes
146 Threads have a number of attributes that may be set at creation time.
147 This is done by filling a thread attribute object @var{attr} of type
148 @code{pthread_attr_t}, then passing it as second argument to
149 @code{pthread_create}. Passing @code{NULL} is equivalent to passing a
150 thread attribute object with all attributes set to their default values.
152 Attribute objects are consulted only when creating a new thread. The
153 same attribute object can be used for creating several threads.
154 Modifying an attribute object after a call to @code{pthread_create} does
155 not change the attributes of the thread previously created.
159 @deftypefun int pthread_attr_init (pthread_attr_t *@var{attr})
160 @code{pthread_attr_init} initializes the thread attribute object
161 @var{attr} and fills it with default values for the attributes. (The
162 default values are listed below for each attribute.)
164 Each attribute @var{attrname} (see below for a list of all attributes)
165 can be individually set using the function
166 @code{pthread_attr_set@var{attrname}} and retrieved using the function
167 @code{pthread_attr_get@var{attrname}}.
172 @deftypefun int pthread_attr_destroy (pthread_attr_t *@var{attr})
173 @code{pthread_attr_destroy} destroys the attribute object pointed to by
174 @var{attr} releasing any resources associated with it. @var{attr} is
175 left in an undefined state, and you must not use it again in a call to
176 any pthreads function until it has been reinitialized.
179 @findex pthread_attr_setinheritsched
180 @findex pthread_attr_setschedparam
181 @findex pthread_attr_setschedpolicy
182 @findex pthread_attr_setscope
185 @deftypefun int pthread_attr_set@var{attr} (pthread_attr_t *@var{obj}, int @var{value})
186 Set attribute @var{attr} to @var{value} in the attribute object pointed
187 to by @var{obj}. See below for a list of possible attributes and the
188 values they can take.
190 On success, these functions return 0. If @var{value} is not meaningful
191 for the @var{attr} being modified, they will return the error code
192 @code{EINVAL}. Some of the functions have other failure modes; see
196 @findex pthread_attr_getinheritsched
197 @findex pthread_attr_getschedparam
198 @findex pthread_attr_getschedpolicy
199 @findex pthread_attr_getscope
202 @deftypefun int pthread_attr_get@var{attr} (const pthread_attr_t *@var{obj}, int *@var{value})
203 Store the current setting of @var{attr} in @var{obj} into the variable
204 pointed to by @var{value}.
206 These functions always return 0.
209 The following thread attributes are supported:
212 Choose whether the thread is created in the joinable state (value
213 @code{PTHREAD_CREATE_JOINABLE}) or in the detached state
214 (@code{PTHREAD_CREATE_DETACHED}). The default is
215 @code{PTHREAD_CREATE_JOINABLE}.
217 In the joinable state, another thread can synchronize on the thread
218 termination and recover its termination code using @code{pthread_join},
219 but some of the thread resources are kept allocated after the thread
220 terminates, and reclaimed only when another thread performs
221 @code{pthread_join} on that thread.
223 In the detached state, the thread resources are immediately freed when
224 it terminates, but @code{pthread_join} cannot be used to synchronize on
225 the thread termination.
227 A thread created in the joinable state can later be put in the detached
228 thread using @code{pthread_detach}.
231 Select the scheduling policy for the thread: one of @code{SCHED_OTHER}
232 (regular, non-realtime scheduling), @code{SCHED_RR} (realtime,
233 round-robin) or @code{SCHED_FIFO} (realtime, first-in first-out).
234 The default is @code{SCHED_OTHER}.
235 @c Not doc'd in our manual: FIXME.
236 @c See @code{sched_setpolicy} for more information on scheduling policies.
238 The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
239 are available only to processes with superuser privileges.
240 @code{pthread_attr_setschedparam} will fail and return @code{ENOTSUP} if
241 you try to set a realtime policy when you are unprivileged.
243 The scheduling policy of a thread can be changed after creation with
244 @code{pthread_setschedparam}.
247 Change the scheduling parameter (the scheduling priority)
248 for the thread. The default is 0.
250 This attribute is not significant if the scheduling policy is
251 @code{SCHED_OTHER}; it only matters for the realtime policies
252 @code{SCHED_RR} and @code{SCHED_FIFO}.
254 The scheduling priority of a thread can be changed after creation with
255 @code{pthread_setschedparam}.
258 Choose whether the scheduling policy and scheduling parameter for the
259 newly created thread are determined by the values of the
260 @var{schedpolicy} and @var{schedparam} attributes (value
261 @code{PTHREAD_EXPLICIT_SCHED}) or are inherited from the parent thread
262 (value @code{PTHREAD_INHERIT_SCHED}). The default is
263 @code{PTHREAD_EXPLICIT_SCHED}.
266 Choose the scheduling contention scope for the created thread. The
267 default is @code{PTHREAD_SCOPE_SYSTEM}, meaning that the threads contend
268 for CPU time with all processes running on the machine. In particular,
269 thread priorities are interpreted relative to the priorities of all
270 other processes on the machine. The other possibility,
271 @code{PTHREAD_SCOPE_PROCESS}, means that scheduling contention occurs
272 only between the threads of the running process: thread priorities are
273 interpreted relative to the priorities of the other threads of the
274 process, regardless of the priorities of other processes.
276 @code{PTHREAD_SCOPE_PROCESS} is not supported in LinuxThreads. If you
277 try to set the scope to this value @code{pthread_attr_setscope} will
278 fail and return @code{ENOTSUP}.
282 @section Cancellation
284 Cancellation is the mechanism by which a thread can terminate the
285 execution of another thread. More precisely, a thread can send a
286 cancellation request to another thread. Depending on its settings, the
287 target thread can then either ignore the request, honor it immediately,
288 or defer it till it reaches a cancellation point. When threads are
289 first created by @code{pthread_create}, they always defer cancellation
292 When a thread eventually honors a cancellation request, it behaves as if
293 @code{pthread_exit(PTHREAD_CANCELED)} was called. All cleanup handlers
294 are executed in reverse order, finalization functions for
295 thread-specific data are called, and finally the thread stops executing.
296 If the cancelled thread was joinable, the return value
297 @code{PTHREAD_CANCELED} is provided to whichever thread calls
298 @var{pthread_join} on it. See @code{pthread_exit} for more information.
300 Cancellation points are the points where the thread checks for pending
301 cancellation requests and performs them. The POSIX threads functions
302 @code{pthread_join}, @code{pthread_cond_wait},
303 @code{pthread_cond_timedwait}, @code{pthread_testcancel},
304 @code{sem_wait}, and @code{sigwait} are cancellation points. In
305 addition, these system calls are cancellation points:
307 @multitable @columnfractions .33 .33 .33
308 @item @t{accept} @tab @t{open} @tab @t{sendmsg}
309 @item @t{close} @tab @t{pause} @tab @t{sendto}
310 @item @t{connect} @tab @t{read} @tab @t{system}
311 @item @t{fcntl} @tab @t{recv} @tab @t{tcdrain}
312 @item @t{fsync} @tab @t{recvfrom} @tab @t{wait}
313 @item @t{lseek} @tab @t{recvmsg} @tab @t{waitpid}
314 @item @t{msync} @tab @t{send} @tab @t{write}
319 All library functions that call these functions (such as
320 @code{printf}) are also cancellation points.
324 @deftypefun int pthread_setcancelstate (int @var{state}, int *@var{oldstate})
325 @code{pthread_setcancelstate} changes the cancellation state for the
326 calling thread -- that is, whether cancellation requests are ignored or
327 not. The @var{state} argument is the new cancellation state: either
328 @code{PTHREAD_CANCEL_ENABLE} to enable cancellation, or
329 @code{PTHREAD_CANCEL_DISABLE} to disable cancellation (cancellation
330 requests are ignored).
332 If @var{oldstate} is not @code{NULL}, the previous cancellation state is
333 stored in the location pointed to by @var{oldstate}, and can thus be
334 restored later by another call to @code{pthread_setcancelstate}.
336 If the @var{state} argument is not @code{PTHREAD_CANCEL_ENABLE} or
337 @code{PTHREAD_CANCEL_DISABLE}, @code{pthread_setcancelstate} fails and
338 returns @code{EINVAL}. Otherwise it returns 0.
343 @deftypefun int pthread_setcanceltype (int @var{type}, int *@var{oldtype})
344 @code{pthread_setcanceltype} changes the type of responses to
345 cancellation requests for the calling thread: asynchronous (immediate)
346 or deferred. The @var{type} argument is the new cancellation type:
347 either @code{PTHREAD_CANCEL_ASYNCHRONOUS} to cancel the calling thread
348 as soon as the cancellation request is received, or
349 @code{PTHREAD_CANCEL_DEFERRED} to keep the cancellation request pending
350 until the next cancellation point. If @var{oldtype} is not @code{NULL},
351 the previous cancellation state is stored in the location pointed to by
352 @var{oldtype}, and can thus be restored later by another call to
353 @code{pthread_setcanceltype}.
355 If the @var{type} argument is not @code{PTHREAD_CANCEL_DEFERRED} or
356 @code{PTHREAD_CANCEL_ASYNCHRONOUS}, @code{pthread_setcanceltype} fails
357 and returns @code{EINVAL}. Otherwise it returns 0.
362 @deftypefun void pthread_testcancel (@var{void})
363 @code{pthread_testcancel} does nothing except testing for pending
364 cancellation and executing it. Its purpose is to introduce explicit
365 checks for cancellation in long sequences of code that do not call
366 cancellation point functions otherwise.
369 @node Cleanup Handlers
370 @section Cleanup Handlers
372 Cleanup handlers are functions that get called when a thread terminates,
373 either by calling @code{pthread_exit} or because of
374 cancellation. Cleanup handlers are installed and removed following a
375 stack-like discipline.
377 The purpose of cleanup handlers is to free the resources that a thread
378 may hold at the time it terminates. In particular, if a thread exits or
379 is cancelled while it owns a locked mutex, the mutex will remain locked
380 forever and prevent other threads from executing normally. The best way
381 to avoid this is, just before locking the mutex, to install a cleanup
382 handler whose effect is to unlock the mutex. Cleanup handlers can be
383 used similarly to free blocks allocated with @code{malloc} or close file
384 descriptors on thread termination.
386 Here is how to lock a mutex @var{mut} in such a way that it will be
387 unlocked if the thread is canceled while @var{mut} is locked:
390 pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
391 pthread_mutex_lock(&mut);
393 pthread_mutex_unlock(&mut);
394 pthread_cleanup_pop(0);
397 Equivalently, the last two lines can be replaced by
400 pthread_cleanup_pop(1);
403 Notice that the code above is safe only in deferred cancellation mode
404 (see @code{pthread_setcanceltype}). In asynchronous cancellation mode, a
405 cancellation can occur between @code{pthread_cleanup_push} and
406 @code{pthread_mutex_lock}, or between @code{pthread_mutex_unlock} and
407 @code{pthread_cleanup_pop}, resulting in both cases in the thread trying
408 to unlock a mutex not locked by the current thread. This is the main
409 reason why asynchronous cancellation is difficult to use.
411 If the code above must also work in asynchronous cancellation mode,
412 then it must switch to deferred mode for locking and unlocking the
416 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
417 pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
418 pthread_mutex_lock(&mut);
420 pthread_cleanup_pop(1);
421 pthread_setcanceltype(oldtype, NULL);
424 The code above can be rewritten in a more compact and efficient way,
425 using the non-portable functions @code{pthread_cleanup_push_defer_np}
426 and @code{pthread_cleanup_pop_restore_np}:
429 pthread_cleanup_push_defer_np(pthread_mutex_unlock, (void *) &mut);
430 pthread_mutex_lock(&mut);
432 pthread_cleanup_pop_restore_np(1);
437 @deftypefun void pthread_cleanup_push (void (*@var{routine}) (void *), void *@var{arg})
439 @code{pthread_cleanup_push} installs the @var{routine} function with
440 argument @var{arg} as a cleanup handler. From this point on to the
441 matching @code{pthread_cleanup_pop}, the function @var{routine} will be
442 called with arguments @var{arg} when the thread terminates, either
443 through @code{pthread_exit} or by cancellation. If several cleanup
444 handlers are active at that point, they are called in LIFO order: the
445 most recently installed handler is called first.
450 @deftypefun void pthread_cleanup_pop (int @var{execute})
451 @code{pthread_cleanup_pop} removes the most recently installed cleanup
452 handler. If the @var{execute} argument is not 0, it also executes the
453 handler, by calling the @var{routine} function with arguments
454 @var{arg}. If the @var{execute} argument is 0, the handler is only
455 removed but not executed.
458 Matching pairs of @code{pthread_cleanup_push} and
459 @code{pthread_cleanup_pop} must occur in the same function, at the same
460 level of block nesting. Actually, @code{pthread_cleanup_push} and
461 @code{pthread_cleanup_pop} are macros, and the expansion of
462 @code{pthread_cleanup_push} introduces an open brace @code{@{} with the
463 matching closing brace @code{@}} being introduced by the expansion of the
464 matching @code{pthread_cleanup_pop}.
468 @deftypefun void pthread_cleanup_push_defer_np (void (*@var{routine}) (void *), void *@var{arg})
469 @code{pthread_cleanup_push_defer_np} is a non-portable extension that
470 combines @code{pthread_cleanup_push} and @code{pthread_setcanceltype}.
471 It pushes a cleanup handler just as @code{pthread_cleanup_push} does,
472 but also saves the current cancellation type and sets it to deferred
473 cancellation. This ensures that the cleanup mechanism is effective even
474 if the thread was initially in asynchronous cancellation mode.
479 @deftypefun void pthread_cleanup_pop_restore_np (int @var{execute})
480 @code{pthread_cleanup_pop_restore_np} pops a cleanup handler introduced
481 by @code{pthread_cleanup_push_defer_np}, and restores the cancellation
482 type to its value at the time @code{pthread_cleanup_push_defer_np} was
486 @code{pthread_cleanup_push_defer_np} and
487 @code{pthread_cleanup_pop_restore_np} must occur in matching pairs, at
488 the same level of block nesting.
493 pthread_cleanup_push_defer_np(routine, arg);
495 pthread_cleanup_pop_defer_np(execute);
499 is functionally equivalent to (but more compact and efficient than)
504 pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
505 pthread_cleanup_push(routine, arg);
507 pthread_cleanup_pop(execute);
508 pthread_setcanceltype(oldtype, NULL);
516 A mutex is a MUTual EXclusion device, and is useful for protecting
517 shared data structures from concurrent modifications, and implementing
518 critical sections and monitors.
520 A mutex has two possible states: unlocked (not owned by any thread),
521 and locked (owned by one thread). A mutex can never be owned by two
522 different threads simultaneously. A thread attempting to lock a mutex
523 that is already locked by another thread is suspended until the owning
524 thread unlocks the mutex first.
526 None of the mutex functions is a cancellation point, not even
527 @code{pthread_mutex_lock}, in spite of the fact that it can suspend a
528 thread for arbitrary durations. This way, the status of mutexes at
529 cancellation points is predictable, allowing cancellation handlers to
530 unlock precisely those mutexes that need to be unlocked before the
531 thread stops executing. Consequently, threads using deferred
532 cancellation should never hold a mutex for extended periods of time.
534 It is not safe to call mutex functions from a signal handler. In
535 particular, calling @code{pthread_mutex_lock} or
536 @code{pthread_mutex_unlock} from a signal handler may deadlock the
541 @deftypefun int pthread_mutex_init (pthread_mutex_t *@var{mutex}, const pthread_mutexattr_t *@var{mutexattr})
543 @code{pthread_mutex_init} initializes the mutex object pointed to by
544 @var{mutex} according to the mutex attributes specified in @var{mutexattr}.
545 If @var{mutexattr} is @code{NULL}, default attributes are used instead.
547 The LinuxThreads implementation supports only one mutex attribute,
548 the @var{mutex kind}, which is either ``fast'', ``recursive'', or
549 ``error checking''. The kind of a mutex determines whether
550 it can be locked again by a thread that already owns it.
551 The default kind is ``fast''.
553 Variables of type @code{pthread_mutex_t} can also be initialized
554 statically, using the constants @code{PTHREAD_MUTEX_INITIALIZER} (for
555 fast mutexes), @code{PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP} (for
556 recursive mutexes), and @code{PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP}
557 (for error checking mutexes).
559 @code{pthread_mutex_init} always returns 0.
564 @deftypefun int pthread_mutex_lock (pthread_mutex_t *mutex))
565 @code{pthread_mutex_lock} locks the given mutex. If the mutex is
566 currently unlocked, it becomes locked and owned by the calling thread,
567 and @code{pthread_mutex_lock} returns immediately. If the mutex is
568 already locked by another thread, @code{pthread_mutex_lock} suspends the
569 calling thread until the mutex is unlocked.
571 If the mutex is already locked by the calling thread, the behavior of
572 @code{pthread_mutex_lock} depends on the kind of the mutex. If the mutex
573 is of the ``fast'' kind, the calling thread is suspended. It will
574 remain suspended forever, because no other thread can unlock the mutex.
575 If the mutex is of the ``error checking'' kind, @code{pthread_mutex_lock}
576 returns immediately with the error code @code{EDEADLK}. If the mutex is
577 of the ``recursive'' kind, @code{pthread_mutex_lock} succeeds and
578 returns immediately, recording the number of times the calling thread
579 has locked the mutex. An equal number of @code{pthread_mutex_unlock}
580 operations must be performed before the mutex returns to the unlocked
586 @deftypefun int pthread_mutex_trylock (pthread_mutex_t *@var{mutex})
587 @code{pthread_mutex_trylock} behaves identically to
588 @code{pthread_mutex_lock}, except that it does not block the calling
589 thread if the mutex is already locked by another thread (or by the
590 calling thread in the case of a ``fast'' mutex). Instead,
591 @code{pthread_mutex_trylock} returns immediately with the error code
597 @deftypefun int pthread_mutex_unlock (pthread_mutex_t *@var{mutex})
598 @code{pthread_mutex_unlock} unlocks the given mutex. The mutex is
599 assumed to be locked and owned by the calling thread on entrance to
600 @code{pthread_mutex_unlock}. If the mutex is of the ``fast'' kind,
601 @code{pthread_mutex_unlock} always returns it to the unlocked state. If
602 it is of the ``recursive'' kind, it decrements the locking count of the
603 mutex (number of @code{pthread_mutex_lock} operations performed on it by
604 the calling thread), and only when this count reaches zero is the mutex
607 On ``error checking'' mutexes, @code{pthread_mutex_unlock} actually
608 checks at run-time that the mutex is locked on entrance, and that it was
609 locked by the same thread that is now calling
610 @code{pthread_mutex_unlock}. If these conditions are not met,
611 @code{pthread_mutex_unlock} returns @code{EPERM}, and the mutex remains
612 unchanged. ``Fast'' and ``recursive'' mutexes perform no such checks,
613 thus allowing a locked mutex to be unlocked by a thread other than its
614 owner. This is non-portable behavior and must not be relied upon.
619 @deftypefun int pthread_mutex_destroy (pthread_mutex_t *@var{mutex})
620 @code{pthread_mutex_destroy} destroys a mutex object, freeing the
621 resources it might hold. The mutex must be unlocked on entrance. In the
622 LinuxThreads implementation, no resources are associated with mutex
623 objects, thus @code{pthread_mutex_destroy} actually does nothing except
624 checking that the mutex is unlocked.
626 If the mutex is locked by some thread, @code{pthread_mutex_destroy}
627 returns @code{EBUSY}. Otherwise it returns 0.
630 If any of the above functions (except @code{pthread_mutex_init})
631 is applied to an uninitialized mutex, they will simply return
632 @code{EINVAL} and do nothing.
634 A shared global variable @var{x} can be protected by a mutex as follows:
638 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
641 All accesses and modifications to @var{x} should be bracketed by calls to
642 @code{pthread_mutex_lock} and @code{pthread_mutex_unlock} as follows:
645 pthread_mutex_lock(&mut);
647 pthread_mutex_unlock(&mut);
650 Mutex attributes can be specified at mutex creation time, by passing a
651 mutex attribute object as second argument to @code{pthread_mutex_init}.
652 Passing @code{NULL} is equivalent to passing a mutex attribute object
653 with all attributes set to their default values.
657 @deftypefun int pthread_mutexattr_init (pthread_mutexattr_t *@var{attr})
658 @code{pthread_mutexattr_init} initializes the mutex attribute object
659 @var{attr} and fills it with default values for the attributes.
661 This function always returns 0.
666 @deftypefun int pthread_mutexattr_destroy (pthread_mutexattr_t *@var{attr})
667 @code{pthread_mutexattr_destroy} destroys a mutex attribute object,
668 which must not be reused until it is
669 reinitialized. @code{pthread_mutexattr_destroy} does nothing in the
670 LinuxThreads implementation.
672 This function always returns 0.
675 LinuxThreads supports only one mutex attribute: the mutex kind, which is
676 either @code{PTHREAD_MUTEX_FAST_NP} for ``fast'' mutexes,
677 @code{PTHREAD_MUTEX_RECURSIVE_NP} for ``recursive'' mutexes, or
678 @code{PTHREAD_MUTEX_ERRORCHECK_NP} for ``error checking'' mutexes. As
679 the @code{NP} suffix indicates, this is a non-portable extension to the
680 POSIX standard and should not be employed in portable programs.
682 The mutex kind determines what happens if a thread attempts to lock a
683 mutex it already owns with @code{pthread_mutex_lock}. If the mutex is of
684 the ``fast'' kind, @code{pthread_mutex_lock} simply suspends the calling
685 thread forever. If the mutex is of the ``error checking'' kind,
686 @code{pthread_mutex_lock} returns immediately with the error code
687 @code{EDEADLK}. If the mutex is of the ``recursive'' kind, the call to
688 @code{pthread_mutex_lock} returns immediately with a success return
689 code. The number of times the thread owning the mutex has locked it is
690 recorded in the mutex. The owning thread must call
691 @code{pthread_mutex_unlock} the same number of times before the mutex
692 returns to the unlocked state.
694 The default mutex kind is ``fast'', that is, @code{PTHREAD_MUTEX_FAST_NP}.
698 @deftypefun int pthread_mutexattr_setkind_np (pthread_mutexattr_t *@var{attr}, int @var{kind})
699 @code{pthread_mutexattr_setkind_np} sets the mutex kind attribute in
700 @var{attr} to the value specified by @var{kind}.
702 If @var{kind} is not @code{PTHREAD_MUTEX_FAST_NP},
703 @code{PTHREAD_MUTEX_RECURSIVE_NP}, or
704 @code{PTHREAD_MUTEX_ERRORCHECK_NP}, this function will return
705 @code{EINVAL} and leave @var{attr} unchanged.
710 @deftypefun int pthread_mutexattr_getkind_np (const pthread_mutexattr_t *@var{attr}, int *@var{kind})
711 @code{pthread_mutexattr_getkind_np} retrieves the current value of the
712 mutex kind attribute in @var{attr} and stores it in the location pointed
715 This function always returns 0.
718 @node Condition Variables
719 @section Condition Variables
721 A condition (short for ``condition variable'') is a synchronization
722 device that allows threads to suspend execution until some predicate on
723 shared data is satisfied. The basic operations on conditions are: signal
724 the condition (when the predicate becomes true), and wait for the
725 condition, suspending the thread execution until another thread signals
728 A condition variable must always be associated with a mutex, to avoid
729 the race condition where a thread prepares to wait on a condition
730 variable and another thread signals the condition just before the first
731 thread actually waits on it.
735 @deftypefun int pthread_cond_init (pthread_cond_t *@var{cond}, pthread_condattr_t *cond_@var{attr})
737 @code{pthread_cond_init} initializes the condition variable @var{cond},
738 using the condition attributes specified in @var{cond_attr}, or default
739 attributes if @var{cond_attr} is @code{NULL}. The LinuxThreads
740 implementation supports no attributes for conditions, hence the
741 @var{cond_attr} parameter is actually ignored.
743 Variables of type @code{pthread_cond_t} can also be initialized
744 statically, using the constant @code{PTHREAD_COND_INITIALIZER}.
746 This function always returns 0.
751 @deftypefun int pthread_cond_signal (pthread_cond_t *@var{cond})
752 @code{pthread_cond_signal} restarts one of the threads that are waiting
753 on the condition variable @var{cond}. If no threads are waiting on
754 @var{cond}, nothing happens. If several threads are waiting on
755 @var{cond}, exactly one is restarted, but it is not specified which.
757 This function always returns 0.
762 @deftypefun int pthread_cond_broadcast (pthread_cond_t *@var{cond})
763 @code{pthread_cond_broadcast} restarts all the threads that are waiting
764 on the condition variable @var{cond}. Nothing happens if no threads are
765 waiting on @var{cond}.
767 This function always returns 0.
772 @deftypefun int pthread_cond_wait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex})
773 @code{pthread_cond_wait} atomically unlocks the @var{mutex} (as per
774 @code{pthread_unlock_mutex}) and waits for the condition variable
775 @var{cond} to be signaled. The thread execution is suspended and does
776 not consume any CPU time until the condition variable is signaled. The
777 @var{mutex} must be locked by the calling thread on entrance to
778 @code{pthread_cond_wait}. Before returning to the calling thread,
779 @code{pthread_cond_wait} re-acquires @var{mutex} (as per
780 @code{pthread_lock_mutex}).
782 Unlocking the mutex and suspending on the condition variable is done
783 atomically. Thus, if all threads always acquire the mutex before
784 signaling the condition, this guarantees that the condition cannot be
785 signaled (and thus ignored) between the time a thread locks the mutex
786 and the time it waits on the condition variable.
788 This function always returns 0.
793 @deftypefun int pthread_cond_timedwait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime})
794 @code{pthread_cond_timedwait} atomically unlocks @var{mutex} and waits
795 on @var{cond}, as @code{pthread_cond_wait} does, but it also bounds the
796 duration of the wait. If @var{cond} has not been signaled before time
797 @var{abstime}, the mutex @var{mutex} is re-acquired and
798 @code{pthread_cond_timedwait} returns the error code @code{ETIMEDOUT}.
799 The wait can also be interrupted by a signal; in that case
800 @code{pthread_cond_timedwait} returns @code{EINTR}.
802 The @var{abstime} parameter specifies an absolute time, with the same
803 origin as @code{time} and @code{gettimeofday}: an @var{abstime} of 0
804 corresponds to 00:00:00 GMT, January 1, 1970.
809 @deftypefun int pthread_cond_destroy (pthread_cond_t *@var{cond})
810 @code{pthread_cond_destroy} destroys the condition variable @var{cond},
811 freeing the resources it might hold. If any threads are waiting on the
812 condition variable, @code{pthread_cond_destroy} leaves @var{cond}
813 untouched and returns @code{EBUSY}. Otherwise it returns 0, and
814 @var{cond} must not be used again until it is reinitialized.
816 In the LinuxThreads implementation, no resources are associated with
817 condition variables, so @code{pthread_cond_destroy} actually does
821 @code{pthread_cond_wait} and @code{pthread_cond_timedwait} are
822 cancellation points. If a thread is cancelled while suspended in one of
823 these functions, the thread immediately resumes execution, relocks the
824 mutex specified by @var{mutex}, and finally executes the cancellation.
825 Consequently, cleanup handlers are assured that @var{mutex} is locked
826 when they are called.
828 It is not safe to call the condition variable functions from a signal
829 handler. In particular, calling @code{pthread_cond_signal} or
830 @code{pthread_cond_broadcast} from a signal handler may deadlock the
833 Consider two shared variables @var{x} and @var{y}, protected by the
834 mutex @var{mut}, and a condition variable @var{cond} that is to be
835 signaled whenever @var{x} becomes greater than @var{y}.
839 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
840 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
843 Waiting until @var{x} is greater than @var{y} is performed as follows:
846 pthread_mutex_lock(&mut);
848 pthread_cond_wait(&cond, &mut);
850 /* operate on x and y */
851 pthread_mutex_unlock(&mut);
854 Modifications on @var{x} and @var{y} that may cause @var{x} to become greater than
855 @var{y} should signal the condition if needed:
858 pthread_mutex_lock(&mut);
860 if (x > y) pthread_mutex_broadcast(&cond);
861 pthread_mutex_unlock(&mut);
864 If it can be proved that at most one waiting thread needs to be waken
865 up (for instance, if there are only two threads communicating through
866 @var{x} and @var{y}), @code{pthread_cond_signal} can be used as a slightly more
867 efficient alternative to @code{pthread_cond_broadcast}. In doubt, use
868 @code{pthread_cond_broadcast}.
870 To wait for @var{x} to becomes greater than @var{y} with a timeout of 5
875 struct timespec timeout;
878 pthread_mutex_lock(&mut);
880 timeout.tv_sec = now.tv_sec + 5;
881 timeout.tv_nsec = now.tv_usec * 1000;
883 while (x <= y && retcode != ETIMEDOUT) @{
884 retcode = pthread_cond_timedwait(&cond, &mut, &timeout);
886 if (retcode == ETIMEDOUT) @{
887 /* timeout occurred */
889 /* operate on x and y */
891 pthread_mutex_unlock(&mut);
894 Condition attributes can be specified at condition creation time, by
895 passing a condition attribute object as second argument to
896 @code{pthread_cond_init}. Passing @code{NULL} is equivalent to passing
897 a condition attribute object with all attributes set to their default
900 The LinuxThreads implementation supports no attributes for
901 conditions. The functions on condition attributes are included only for
902 compliance with the POSIX standard.
906 @deftypefun int pthread_condattr_init (pthread_condattr_t *@var{attr})
907 @deftypefunx int pthread_condattr_destroy (pthread_condattr_t *@var{attr})
908 @code{pthread_condattr_init} initializes the condition attribute object
909 @var{attr} and fills it with default values for the attributes.
910 @code{pthread_condattr_destroy} destroys the condition attribute object
913 Both functions do nothing in the LinuxThreads implementation.
915 @code{pthread_condattr_init} and @code{pthread_condattr_destroy} always
919 @node POSIX Semaphores
920 @section POSIX Semaphores
922 @vindex SEM_VALUE_MAX
923 Semaphores are counters for resources shared between threads. The
924 basic operations on semaphores are: increment the counter atomically,
925 and wait until the counter is non-null and decrement it atomically.
927 Semaphores have a maximum value past which they cannot be incremented.
928 The macro @code{SEM_VALUE_MAX} is defined to be this maximum value. In
929 the GNU C library, @code{SEM_VALUE_MAX} is equal to @code{INT_MAX}
930 (@pxref{Range of Type}), but it may be much smaller on other systems.
932 The pthreads library implements POSIX 1003.1b semaphores. These should
933 not be confused with System V semaphores (@code{ipc}, @code{semctl} and
935 @c !!! SysV IPC is not doc'd at all in our manual
937 All the semaphore functions and macros are defined in @file{semaphore.h}.
941 @deftypefun int sem_init (sem_t *@var{sem}, int @var{pshared}, unsigned int @var{value})
942 @code{sem_init} initializes the semaphore object pointed to by
943 @var{sem}. The count associated with the semaphore is set initially to
944 @var{value}. The @var{pshared} argument indicates whether the semaphore
945 is local to the current process (@var{pshared} is zero) or is to be
946 shared between several processes (@var{pshared} is not zero).
948 On success @code{sem_init} returns 0. On failure it returns -1 and sets
949 @var{errno} to one of the following values:
953 @var{value} exceeds the maximal counter value @code{SEM_VALUE_MAX}
956 @var{pshared} is not zero. LinuxThreads currently does not support
957 process-shared semaphores. (This will eventually change.)
963 @deftypefun int sem_destroy (sem_t * @var{sem})
964 @code{sem_destroy} destroys a semaphore object, freeing the resources it
965 might hold. If any threads are waiting on the semaphore when
966 @code{sem_destroy} is called, it fails and sets @var{errno} to
969 In the LinuxThreads implementation, no resources are associated with
970 semaphore objects, thus @code{sem_destroy} actually does nothing except
971 checking that no thread is waiting on the semaphore. This will change
972 when process-shared semaphores are implemented.
977 @deftypefun int sem_wait (sem_t * @var{sem})
978 @code{sem_wait} suspends the calling thread until the semaphore pointed
979 to by @var{sem} has non-zero count. It then atomically decreases the
982 @code{sem_wait} is a cancellation point. It always returns 0.
987 @deftypefun int sem_trywait (sem_t * @var{sem})
988 @code{sem_trywait} is a non-blocking variant of @code{sem_wait}. If the
989 semaphore pointed to by @var{sem} has non-zero count, the count is
990 atomically decreased and @code{sem_trywait} immediately returns 0. If
991 the semaphore count is zero, @code{sem_trywait} immediately returns -1
992 and sets errno to @code{EAGAIN}.
997 @deftypefun int sem_post (sem_t * @var{sem})
998 @code{sem_post} atomically increases the count of the semaphore pointed to
999 by @var{sem}. This function never blocks.
1001 @c !!! This para appears not to agree with the code.
1002 On processors supporting atomic compare-and-swap (Intel 486, Pentium and
1003 later, Alpha, PowerPC, MIPS II, Motorola 68k, Ultrasparc), the
1004 @code{sem_post} function is can safely be called from signal handlers.
1005 This is the only thread synchronization function provided by POSIX
1006 threads that is async-signal safe. On the Intel 386 and earlier Sparc
1007 chips, the current LinuxThreads implementation of @code{sem_post} is not
1008 async-signal safe, because the hardware does not support the required
1011 @code{sem_post} always succeeds and returns 0, unless the semaphore
1012 count would exceed @code{SEM_VALUE_MAX} after being incremented. In
1013 that case @code{sem_post} returns -1 and sets @var{errno} to
1014 @code{EINVAL}. The semaphore count is left unchanged.
1017 @comment semaphore.h
1019 @deftypefun int sem_getvalue (sem_t * @var{sem}, int * @var{sval})
1020 @code{sem_getvalue} stores in the location pointed to by @var{sval} the
1021 current count of the semaphore @var{sem}. It always returns 0.
1024 @node Thread-Specific Data
1025 @section Thread-Specific Data
1027 Programs often need global or static variables that have different
1028 values in different threads. Since threads share one memory space, this
1029 cannot be achieved with regular variables. Thread-specific data is the
1030 POSIX threads answer to this need.
1032 Each thread possesses a private memory block, the thread-specific data
1033 area, or TSD area for short. This area is indexed by TSD keys. The TSD
1034 area associates values of type @code{void *} to TSD keys. TSD keys are
1035 common to all threads, but the value associated with a given TSD key can
1036 be different in each thread.
1038 For concreteness, the TSD areas can be viewed as arrays of @code{void *}
1039 pointers, TSD keys as integer indices into these arrays, and the value
1040 of a TSD key as the value of the corresponding array element in the
1043 When a thread is created, its TSD area initially associates @code{NULL}
1048 @deftypefun int pthread_key_create (pthread_key_t *@var{key}, void (*destr_function) (void *))
1049 @code{pthread_key_create} allocates a new TSD key. The key is stored in
1050 the location pointed to by @var{key}. There is a limit of
1051 @code{PTHREAD_KEYS_MAX} on the number of keys allocated at a given
1052 time. The value initially associated with the returned key is
1053 @code{NULL} in all currently executing threads.
1055 The @var{destr_function} argument, if not @code{NULL}, specifies a
1056 destructor function associated with the key. When a thread terminates
1057 via @code{pthread_exit} or by cancellation, @var{destr_function} is
1058 called on the value associated with the key in that thread. The
1059 @var{destr_function} is not called if a key is deleted with
1060 @code{pthread_key_delete} or a value is changed with
1061 @code{pthread_setspecific}. The order in which destructor functions are
1062 called at thread termination time is unspecified.
1064 Before the destructor function is called, the @code{NULL} value is
1065 associated with the key in the current thread. A destructor function
1066 might, however, re-associate non-@code{NULL} values to that key or some
1067 other key. To deal with this, if after all the destructors have been
1068 called for all non-@code{NULL} values, there are still some
1069 non-@code{NULL} values with associated destructors, then the process is
1070 repeated. The LinuxThreads implementation stops the process after
1071 @code{PTHREAD_DESTRUCTOR_ITERATIONS} iterations, even if some
1072 non-@code{NULL} values with associated descriptors remain. Other
1073 implementations may loop indefinitely.
1075 @code{pthread_key_create} returns 0 unless @code{PTHREAD_KEYS_MAX} keys
1076 have already been allocated, in which case it fails and returns
1083 @deftypefun int pthread_key_delete (pthread_key_t @var{key})
1084 @code{pthread_key_delete} deallocates a TSD key. It does not check
1085 whether non-@code{NULL} values are associated with that key in the
1086 currently executing threads, nor call the destructor function associated
1089 If there is no such key @var{key}, it returns @code{EINVAL}. Otherwise
1095 @deftypefun int pthread_setspecific (pthread_key_t @var{key}, const void *@var{pointer})
1096 @code{pthread_setspecific} changes the value associated with @var{key}
1097 in the calling thread, storing the given @var{pointer} instead.
1099 If there is no such key @var{key}, it returns @code{EINVAL}. Otherwise
1105 @deftypefun {void *} pthread_getspecific (pthread_key_t @var{key})
1106 @code{pthread_getspecific} returns the value currently associated with
1107 @var{key} in the calling thread.
1109 If there is no such key @var{key}, it returns @code{NULL}.
1112 The following code fragment allocates a thread-specific array of 100
1113 characters, with automatic reclaimation at thread exit:
1116 /* Key for the thread-specific buffer */
1117 static pthread_key_t buffer_key;
1119 /* Once-only initialisation of the key */
1120 static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
1122 /* Allocate the thread-specific buffer */
1123 void buffer_alloc(void)
1125 pthread_once(&buffer_key_once, buffer_key_alloc);
1126 pthread_setspecific(buffer_key, malloc(100));
1129 /* Return the thread-specific buffer */
1130 char * get_buffer(void)
1132 return (char *) pthread_getspecific(buffer_key);
1135 /* Allocate the key */
1136 static void buffer_key_alloc()
1138 pthread_key_create(&buffer_key, buffer_destroy);
1141 /* Free the thread-specific buffer */
1142 static void buffer_destroy(void * buf)
1148 @node Threads and Signal Handling
1149 @section Threads and Signal Handling
1153 @deftypefun int pthread_sigmask (int @var{how}, const sigset_t *@var{newmask}, sigset_t *@var{oldmask})
1154 @code{pthread_sigmask} changes the signal mask for the calling thread as
1155 described by the @var{how} and @var{newmask} arguments. If @var{oldmask}
1156 is not @code{NULL}, the previous signal mask is stored in the location
1157 pointed to by @var{oldmask}.
1159 The meaning of the @var{how} and @var{newmask} arguments is the same as
1160 for @code{sigprocmask}. If @var{how} is @code{SIG_SETMASK}, the signal
1161 mask is set to @var{newmask}. If @var{how} is @code{SIG_BLOCK}, the
1162 signals specified to @var{newmask} are added to the current signal mask.
1163 If @var{how} is @code{SIG_UNBLOCK}, the signals specified to
1164 @var{newmask} are removed from the current signal mask.
1166 Recall that signal masks are set on a per-thread basis, but signal
1167 actions and signal handlers, as set with @code{sigaction}, are shared
1168 between all threads.
1170 The @code{pthread_sigmask} function returns 0 on success, and one of the
1171 following error codes on error:
1174 @var{how} is not one of @code{SIG_SETMASK}, @code{SIG_BLOCK}, or @code{SIG_UNBLOCK}
1177 @var{newmask} or @var{oldmask} point to invalid addresses
1183 @deftypefun int pthread_kill (pthread_t @var{thread}, int @var{signo})
1184 @code{pthread_kill} sends signal number @var{signo} to the thread
1185 @var{thread}. The signal is delivered and handled as described in
1186 @ref{Signal Handling}.
1188 @code{pthread_kill} returns 0 on success, one of the following error codes
1192 @var{signo} is not a valid signal number
1195 The thread @var{thread} does not exist (e.g. it has already terminated)
1201 @deftypefun int sigwait (const sigset_t *@var{set}, int *@var{sig})
1202 @code{sigwait} suspends the calling thread until one of the signals in
1203 @var{set} is delivered to the calling thread. It then stores the number
1204 of the signal received in the location pointed to by @var{sig} and
1205 returns. The signals in @var{set} must be blocked and not ignored on
1206 entrance to @code{sigwait}. If the delivered signal has a signal handler
1207 function attached, that function is @emph{not} called.
1209 @code{sigwait} is a cancellation point. It always returns 0.
1212 For @code{sigwait} to work reliably, the signals being waited for must be
1213 blocked in all threads, not only in the calling thread, since
1214 otherwise the POSIX semantics for signal delivery do not guarantee
1215 that it's the thread doing the @code{sigwait} that will receive the signal.
1216 The best way to achieve this is block those signals before any threads
1217 are created, and never unblock them in the program other than by
1218 calling @code{sigwait}.
1220 Signal handling in LinuxThreads departs significantly from the POSIX
1221 standard. According to the standard, ``asynchronous'' (external) signals
1222 are addressed to the whole process (the collection of all threads),
1223 which then delivers them to one particular thread. The thread that
1224 actually receives the signal is any thread that does not currently block
1227 In LinuxThreads, each thread is actually a kernel process with its own
1228 PID, so external signals are always directed to one particular thread.
1229 If, for instance, another thread is blocked in @code{sigwait} on that
1230 signal, it will not be restarted.
1232 The LinuxThreads implementation of @code{sigwait} installs dummy signal
1233 handlers for the signals in @var{set} for the duration of the
1234 wait. Since signal handlers are shared between all threads, other
1235 threads must not attach their own signal handlers to these signals, or
1236 alternatively they should all block these signals (which is recommended
1239 @node Miscellaneous Thread Functions
1240 @section Miscellaneous Thread Functions
1244 @deftypefun {pthread_t} pthread_self (@var{void})
1245 @code{pthread_self} returns the thread identifier for the calling thread.
1250 @deftypefun int pthread_equal (pthread_t thread1, pthread_t thread2)
1251 @code{pthread_equal} determines if two thread identifiers refer to the same
1254 A non-zero value is returned if @var{thread1} and @var{thread2} refer to
1255 the same thread. Otherwise, 0 is returned.
1260 @deftypefun int pthread_detach (pthread_t @var{th})
1261 @code{pthread_detach} puts the thread @var{th} in the detached
1262 state. This guarantees that the memory resources consumed by @var{th}
1263 will be freed immediately when @var{th} terminates. However, this
1264 prevents other threads from synchronizing on the termination of @var{th}
1265 using @code{pthread_join}.
1267 A thread can be created initially in the detached state, using the
1268 @code{detachstate} attribute to @code{pthread_create}. In contrast,
1269 @code{pthread_detach} applies to threads created in the joinable state,
1270 and which need to be put in the detached state later.
1272 After @code{pthread_detach} completes, subsequent attempts to perform
1273 @code{pthread_join} on @var{th} will fail. If another thread is already
1274 joining the thread @var{th} at the time @code{pthread_detach} is called,
1275 @code{pthread_detach} does nothing and leaves @var{th} in the joinable
1278 On success, 0 is returned. On error, one of the following codes is
1282 No thread could be found corresponding to that specified by @var{th}
1284 The thread @var{th} is already in the detached state
1290 @deftypefun int pthread_atfork (void (*@var{prepare})(void), void (*@var{parent})(void), void (*@var{child})(void))
1292 @code{pthread_atfork} registers handler functions to be called just
1293 before and just after a new process is created with @code{fork}. The
1294 @var{prepare} handler will be called from the parent process, just
1295 before the new process is created. The @var{parent} handler will be
1296 called from the parent process, just before @code{fork} returns. The
1297 @var{child} handler will be called from the child process, just before
1298 @code{fork} returns.
1300 @code{pthread_atfork} returns 0 on success and a non-zero error code on
1303 One or more of the three handlers @var{prepare}, @var{parent} and
1304 @var{child} can be given as @code{NULL}, meaning that no handler needs
1305 to be called at the corresponding point.
1307 @code{pthread_atfork} can be called several times to install several
1308 sets of handlers. At @code{fork} time, the @var{prepare} handlers are
1309 called in LIFO order (last added with @code{pthread_atfork}, first
1310 called before @code{fork}), while the @var{parent} and @var{child}
1311 handlers are called in FIFO order (first added, first called).
1313 If there is insufficient memory available to register the handlers,
1314 @code{pthread_atfork} fails and returns @code{ENOMEM}. Otherwise it
1318 To understand the purpose of @code{pthread_atfork}, recall that
1319 @code{fork} duplicates the whole memory space, including mutexes in
1320 their current locking state, but only the calling thread: other threads
1321 are not running in the child process. Thus, if a mutex is locked by a
1322 thread other than the thread calling @code{fork}, that mutex will remain
1323 locked forever in the child process, possibly blocking the execution of
1324 the child process. To avoid this, install handlers with
1325 @code{pthread_atfork} as follows: the @var{prepare} handler locks the
1326 global mutexes (in locking order), and the @var{parent} and @var{child}
1327 handlers unlock them (in reverse order). Alternatively, @var{prepare}
1328 and @var{parent} can be set to @code{NULL} and @var{child} to a function
1329 that calls @code{pthread_mutex_init} on the global mutexes.
1333 @deftypefun void pthread_kill_other_threads_np (@var{void})
1334 @code{pthread_kill_other_threads_np} is a non-portable LinuxThreads extension.
1335 It causes all threads in the program to terminate immediately, except
1336 the calling thread which proceeds normally. It is intended to be
1337 called just before a thread calls one of the @code{exec} functions,
1340 Termination of the other threads is not performed through
1341 @code{pthread_cancel} and completely bypasses the cancellation
1342 mechanism. Hence, the current settings for cancellation state and
1343 cancellation type are ignored, and the cleanup handlers are not
1344 executed in the terminated threads.
1346 According to POSIX 1003.1c, a successful @code{exec*} in one of the
1347 threads should automatically terminate all other threads in the program.
1348 This behavior is not yet implemented in LinuxThreads. Calling
1349 @code{pthread_kill_other_threads_np} before @code{exec*} achieves much
1350 of the same behavior, except that if @code{exec*} ultimately fails, then
1351 all other threads are already killed.
1356 @deftypefun int pthread_once (pthread_once_t *once_@var{control}, void (*@var{init_routine}) (void))
1358 The purpose of @code{pthread_once} is to ensure that a piece of
1359 initialization code is executed at most once. The @var{once_control}
1360 argument points to a static or extern variable statically initialized
1361 to @code{PTHREAD_ONCE_INIT}.
1363 The first time @code{pthread_once} is called with a given
1364 @var{once_control} argument, it calls @var{init_routine} with no
1365 argument and changes the value of the @var{once_control} variable to
1366 record that initialization has been performed. Subsequent calls to
1367 @code{pthread_once} with the same @code{once_control} argument do
1370 @code{pthread_once} always returns 0.
1375 @deftypefun int pthread_setschedparam (pthread_t target_@var{thread}, int @var{policy}, const struct sched_param *@var{param})
1377 @code{pthread_setschedparam} sets the scheduling parameters for the
1378 thread @var{target_thread} as indicated by @var{policy} and
1379 @var{param}. @var{policy} can be either @code{SCHED_OTHER} (regular,
1380 non-realtime scheduling), @code{SCHED_RR} (realtime, round-robin) or
1381 @code{SCHED_FIFO} (realtime, first-in first-out). @var{param} specifies
1382 the scheduling priority for the two realtime policies. See
1383 @code{sched_setpolicy} for more information on scheduling policies.
1385 The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
1386 are available only to processes with superuser privileges.
1388 On success, @code{pthread_setschedparam} returns 0. On error it returns
1389 one of the following codes:
1392 @var{policy} is not one of @code{SCHED_OTHER}, @code{SCHED_RR},
1393 @code{SCHED_FIFO}, or the priority value specified by @var{param} is not
1394 valid for the specified policy
1397 Realtime scheduling was requested but the calling process does not have
1398 sufficient privileges.
1401 The @var{target_thread} is invalid or has already terminated
1404 @var{param} points outside the process memory space
1410 @deftypefun int pthread_getschedparam (pthread_t target_@var{thread}, int *@var{policy}, struct sched_param *@var{param})
1412 @code{pthread_getschedparam} retrieves the scheduling policy and
1413 scheduling parameters for the thread @var{target_thread} and stores them
1414 in the locations pointed to by @var{policy} and @var{param},
1417 @code{pthread_getschedparam} returns 0 on success, or one of the
1418 following error codes on failure:
1421 The @var{target_thread} is invalid or has already terminated.
1424 @var{policy} or @var{param} point outside the process memory space.