source: trunk/libs/newlib/src/newlib/libc/sys/linux/linuxthreads/linuxthreads.texi

Last change on this file was 444, checked in by satin@…, 6 years ago

add newlib,libalmos-mkh, restructure shared_syscalls.h and mini-libc

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