2 @c @node Threads, Dynamic Linker, Debugging Support, Top
3 @c %MENU% Functions, constants, and data types for working with threads
7 This chapter describes functions used for managing threads.
8 @Theglibc{} provides two threading implementations: ISO C threads and
12 * ISO C Threads:: Threads based on the ISO C specification.
13 * POSIX Threads:: Threads based on the POSIX specification.
18 @section ISO C Threads
23 This section describes the @glibcadj{} ISO C threads implementation.
24 To have a deeper understanding of this API, it is strongly recommended
25 to read ISO/IEC 9899:2011, section 7.26, in which ISO C threads were
26 originally specified. All types and function prototypes are declared
27 in the header file @file{threads.h}.
30 * ISO C Threads Return Values:: Symbolic constants that represent a
31 function's return value.
32 * ISO C Thread Management:: Support for basic threading.
33 * Call Once:: Single-call functions and macros.
34 * ISO C Mutexes:: A low-level mechanism for mutual exclusion.
35 * ISO C Condition Variables:: High-level objects for thread synchronization.
36 * ISO C Thread-local Storage:: Functions to support thread-local storage.
40 @node ISO C Threads Return Values
41 @subsection Return Values
43 The ISO C thread specification provides the following enumeration
44 constants for return values from functions in the API:
48 @standards{C11, threads.h}
49 A specified time was reached without acquiring the requested resource,
50 usually a mutex or condition variable.
53 @standards{C11, threads.h}
54 The requested operation succeeded.
57 @standards{C11, threads.h}
58 The requested operation failed because a requested resource is already
62 @standards{C11, threads.h}
63 The requested operation failed.
66 @standards{C11, threads.h}
67 The requested operation failed because it was unable to allocate
72 @node ISO C Thread Management
73 @subsection Creation and Control
74 @cindex thread creation
75 @cindex thread control
76 @cindex thread management
78 @Theglibc{} implements a set of functions that allow the user to easily
79 create and use threads. Additional functionality is provided to control
80 the behavior of threads.
82 The following data types are defined for managing threads:
84 @deftp {Data Type} thrd_t
85 @standards{C11, threads.h}
86 A unique object that identifies a thread.
89 @deftp {Data Type} thrd_start_t
90 @standards{C11, threads.h}
91 This data type is an @code{int (*) (void *)} typedef that is passed to
92 @code{thrd_create} when creating a new thread. It should point to the
93 first function that thread will run.
96 The following functions are used for working with threads:
98 @deftypefun int thrd_create (thrd_t *@var{thr}, thrd_start_t @var{func}, void *@var{arg})
99 @standards{C11, threads.h}
100 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
101 @code{thrd_create} creates a new thread that will execute the function
102 @var{func}. The object pointed to by @var{arg} will be used as the
103 argument to @var{func}. If successful, @var{thr} is set to the new
106 This function may return @code{thrd_success}, @code{thrd_nomem}, or
110 @deftypefun thrd_t thrd_current (void)
111 @standards{C11, threads.h}
112 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
113 This function returns the identifier of the calling thread.
116 @deftypefun int thrd_equal (thrd_t @var{lhs}, thrd_t @var{rhs})
117 @standards{C11, threads.h}
118 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
119 @code{thrd_equal} checks whether @var{lhs} and @var{rhs} refer to the
120 same thread. If @var{lhs} and @var{rhs} are different threads, this
121 function returns @math{0}; otherwise, the return value is non-zero.
124 @deftypefun int thrd_sleep (const struct timespec *@var{time_point}, struct timespec *@var{remaining})
125 @standards{C11, threads.h}
126 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
127 @code{thrd_sleep} blocks the execution of the current thread for at
128 least until the elapsed time pointed to by @var{time_point} has been
129 reached. This function does not take an absolute time, but a duration
130 that the thread is required to be blocked. @xref{Time Basics}, and
133 The thread may wake early if a signal that is not ignored is received.
134 In such a case, if @code{remaining} is not NULL, the remaining time
135 duration is stored in the object pointed to by
138 @code{thrd_sleep} returns @math{0} if it blocked for at least the
139 amount of time in @code{time_point}, @math{-1} if it was interrupted
140 by a signal, or a negative number on failure.
143 @deftypefun void thrd_yield (void)
144 @standards{C11, threads.h}
145 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
146 @code{thrd_yield} provides a hint to the implementation to reschedule
147 the execution of the current thread, allowing other threads to run.
150 @deftypefun {_Noreturn void} thrd_exit (int @var{res})
151 @standards{C11, threads.h}
152 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
153 @code{thrd_exit} terminates execution of the calling thread and sets
154 its result code to @var{res}.
156 If this function is called from a single-threaded process, the call is
157 equivalent to calling @code{exit} with @code{EXIT_SUCCESS}
158 (@pxref{Normal Termination}). Also note that returning from a
159 function that started a thread is equivalent to calling
163 @deftypefun int thrd_detach (thrd_t @var{thr})
164 @standards{C11, threads.h}
165 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
166 @code{thrd_detach} detaches the thread identified by @code{thr} from
167 the current control thread. The resources held by the detached thread
168 will be freed automatically once the thread exits. The parent thread
169 will never be notified by any @var{thr} signal.
171 Calling @code{thrd_detach} on a thread that was previously detached or
172 joined by another thread results in undefined behavior.
174 This function returns either @code{thrd_success} or @code{thrd_error}.
177 @deftypefun int thrd_join (thrd_t @var{thr}, int *@var{res})
178 @standards{C11, threads.h}
179 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
180 @code{thrd_join} blocks the current thread until the thread identified
181 by @code{thr} finishes execution. If @code{res} is not NULL, the
182 result code of the thread is put into the location pointed to by
183 @var{res}. The termination of the thread @dfn{synchronizes-with} the
184 completion of this function, meaning both threads have arrived at a
185 common point in their execution.
187 Calling @code{thrd_join} on a thread that was previously detached or
188 joined by another thread results in undefined behavior.
190 This function returns either @code{thrd_success} or @code{thrd_error}.
195 @subsection Call Once
197 @cindex single-call functions
199 In order to guarantee single access to a function, @theglibc{}
200 implements a @dfn{call once function} to ensure a function is only
201 called once in the presence of multiple, potentially calling threads.
203 @deftp {Data Type} once_flag
204 @standards{C11, threads.h}
205 A complete object type capable of holding a flag used by @code{call_once}.
208 @defvr Macro ONCE_FLAG_INIT
209 @standards{C11, threads.h}
210 This value is used to initialize an object of type @code{once_flag}.
213 @deftypefun void call_once (once_flag *@var{flag}, void (*@var{func}) (void))
214 @standards{C11, threads.h}
215 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
216 @code{call_once} calls function @var{func} exactly once, even if
217 invoked from several threads. The completion of the function
218 @var{func} synchronizes-with all previous or subsequent calls to
219 @code{call_once} with the same @code{flag} variable.
226 @cindex mutual exclusion
228 To have better control of resources and how threads access them,
229 @theglibc{} implements a @dfn{mutex} object, which can help avoid race
230 conditions and other concurrency issues. The term ``mutex'' refers to
233 The fundamental data type for a mutex is the @code{mtx_t}:
235 @deftp {Data Type} mtx_t
236 @standards{C11, threads.h}
237 The @code{mtx_t} data type uniquely identifies a mutex object.
240 The ISO C standard defines several types of mutexes. They are
241 represented by the following symbolic constants:
245 @standards{C11, threads.h}
246 A mutex that does not support timeout, or test and return.
249 @standards{C11, threads.h}
250 A mutex that supports recursive locking, which means that the owning
251 thread can lock it more than once without causing deadlock.
254 @standards{C11, threads.h}
255 A mutex that supports timeout.
258 The following functions are used for working with mutexes:
260 @deftypefun int mtx_init (mtx_t *@var{mutex}, int @var{type})
261 @standards{C11, threads.h}
262 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
263 @code{mtx_init} creates a new mutex object with type @var{type}. The
264 object pointed to by @var{mutex} is set to the identifier of the newly
267 Not all combinations of mutex types are valid for the @code{type}
268 argument. Valid uses of mutex types for the @code{type} argument are:
272 A non-recursive mutex that does not support timeout.
275 A non-recursive mutex that does support timeout.
277 @item mtx_plain | mtx_recursive
278 A recursive mutex that does not support timeout.
280 @item mtx_timed | mtx_recursive
281 A recursive mutex that does support timeout.
284 This function returns either @code{thrd_success} or @code{thrd_error}.
287 @deftypefun int mtx_lock (mtx_t *@var{mutex})
288 @standards{C11, threads.h}
289 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
290 @code{mtx_lock} blocks the current thread until the mutex pointed to
291 by @var{mutex} is locked. The behavior is undefined if the current
292 thread has already locked the mutex and the mutex is not recursive.
294 Prior calls to @code{mtx_unlock} on the same mutex synchronize-with
295 this operation (if this operation succeeds), and all lock/unlock
296 operations on any given mutex form a single total order (similar to
297 the modification order of an atomic).
299 This function returns either @code{thrd_success} or @code{thrd_error}.
302 @deftypefun int mtx_timedlock (mtx_t *restrict @var{mutex}, const struct timespec *restrict @var{time_point})
303 @standards{C11, threads.h}
304 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
305 @code{mtx_timedlock} blocks the current thread until the mutex pointed
306 to by @var{mutex} is locked or until the calendar time pointed to by
307 @var{time_point} has been reached. Since this function takes an
308 absolute time, if a duration is required, the calendar time must be
309 calculated manually. @xref{Time Basics}, and @ref{Calendar Time}.
311 If the current thread has already locked the mutex and the mutex is
312 not recursive, or if the mutex does not support timeout, the behavior
313 of this function is undefined.
315 Prior calls to @code{mtx_unlock} on the same mutex synchronize-with
316 this operation (if this operation succeeds), and all lock/unlock
317 operations on any given mutex form a single total order (similar to
318 the modification order of an atomic).
320 This function returns either @code{thrd_success} or @code{thrd_error}.
323 @deftypefun int mtx_trylock (mtx_t *@var{mutex})
324 @standards{C11, threads.h}
325 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
326 @code{mtx_trylock} tries to lock the mutex pointed to by @var{mutex}
327 without blocking. It returns immediately if the mutex is already
330 Prior calls to @code{mtx_unlock} on the same mutex synchronize-with
331 this operation (if this operation succeeds), and all lock/unlock
332 operations on any given mutex form a single total order (similar to
333 the modification order of an atomic).
335 This function returns @code{thrd_success} if the lock was obtained,
336 @code{thrd_busy} if the mutex is already locked, and @code{thrd_error}
340 @deftypefun int mtx_unlock (mtx_t *@var{mutex})
341 @standards{C11, threads.h}
342 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
343 @code{mtx_unlock} unlocks the mutex pointed to by @var{mutex}. The
344 behavior is undefined if the mutex is not locked by the calling
347 This function synchronizes-with subsequent @code{mtx_lock},
348 @code{mtx_trylock}, and @code{mtx_timedlock} calls on the same mutex.
349 All lock/unlock operations on any given mutex form a single total
350 order (similar to the modification order of an atomic).
352 This function returns either @code{thrd_success} or @code{thrd_error}.
355 @deftypefun void mtx_destroy (mtx_t *@var{mutex})
356 @standards{C11, threads.h}
357 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
358 @code{mtx_destroy} destroys the mutex pointed to by @var{mutex}. If
359 there are any threads waiting on the mutex, the behavior is
364 @node ISO C Condition Variables
365 @subsection Condition Variables
367 @cindex condition variables
369 Mutexes are not the only synchronization mechanisms available. For
370 some more complex tasks, @theglibc{} also implements @dfn{condition
371 variables}, which allow the programmer to think at a higher level when
372 solving complex synchronization problems. They are used to
373 synchronize threads waiting on a certain condition to happen.
375 The fundamental data type for condition variables is the @code{cnd_t}:
377 @deftp {Data Type} cnd_t
378 @standards{C11, threads.h}
379 The @code{cnd_t} uniquely identifies a condition variable object.
382 The following functions are used for working with condition variables:
384 @deftypefun int cnd_init (cnd_t *@var{cond})
385 @standards{C11, threads.h}
386 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
387 @code{cnd_init} initializes a new condition variable, identified by
390 This function may return @code{thrd_success}, @code{thrd_nomem}, or
394 @deftypefun int cnd_signal (cnd_t *@var{cond})
395 @standards{C11, threads.h}
396 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
397 @code{cnd_signal} unblocks one thread that is currently waiting on the
398 condition variable pointed to by @var{cond}. If a thread is
399 successfully unblocked, this function returns @code{thrd_success}. If
400 no threads are blocked, this function does nothing and returns
401 @code{thrd_success}. Otherwise, this function returns
405 @deftypefun int cnd_broadcast (cnd_t *@var{cond})
406 @standards{C11, threads.h}
407 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
408 @code{cnd_broadcast} unblocks all the threads that are currently
409 waiting on the condition variable pointed to by @var{cond}. This
410 function returns @code{thrd_success} on success. If no threads are
411 blocked, this function does nothing and returns
412 @code{thrd_success}. Otherwise, this function returns
416 @deftypefun int cnd_wait (cnd_t *@var{cond}, mtx_t *@var{mutex})
417 @standards{C11, threads.h}
418 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
419 @code{cnd_wait} atomically unlocks the mutex pointed to by @var{mutex}
420 and blocks on the condition variable pointed to by @var{cond} until
421 the thread is signaled by @code{cnd_signal} or @code{cnd_broadcast}.
422 The mutex is locked again before the function returns.
424 This function returns either @code{thrd_success} or @code{thrd_error}.
427 @deftypefun int cnd_timedwait (cnd_t *restrict @var{cond}, mtx_t *restrict @var{mutex}, const struct timespec *restrict @var{time_point})
428 @standards{C11, threads.h}
429 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
430 @code{cnd_timedwait} atomically unlocks the mutex pointed to by
431 @var{mutex} and blocks on the condition variable pointed to by
432 @var{cond} until the thread is signaled by @code{cnd_signal} or
433 @code{cnd_broadcast}, or until the calendar time pointed to by
434 @var{time_point} has been reached. The mutex is locked again before
435 the function returns.
437 As for @code{mtx_timedlock}, since this function takes an absolute
438 time, if a duration is required, the calendar time must be calculated
439 manually. @xref{Time Basics}, and @ref{Calendar Time}.
441 This function may return @code{thrd_success}, @code{thrd_nomem}, or
445 @deftypefun void cnd_destroy (cnd_t *@var{cond})
446 @standards{C11, threads.h}
447 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
448 @code{cnd_destroy} destroys the condition variable pointed to by
449 @var{cond}. If there are threads waiting on @var{cond}, the behavior
454 @node ISO C Thread-local Storage
455 @subsection Thread-local Storage
456 @cindex thread-local storage
458 @Theglibc{} implements functions to provide @dfn{thread-local
459 storage}, a mechanism by which variables can be defined to have unique
460 per-thread storage, lifetimes that match the thread lifetime, and
461 destructors that cleanup the unique per-thread storage.
463 Several data types and macros exist for working with thread-local
466 @deftp {Data Type} tss_t
467 @standards{C11, threads.h}
468 The @code{tss_t} data type identifies a thread-specific storage
469 object. Even if shared, every thread will have its own instance of
470 the variable, with different values.
473 @deftp {Data Type} tss_dtor_t
474 @standards{C11, threads.h}
475 The @code{tss_dtor_t} is a function pointer of type @code{void (*)
476 (void *)}, to be used as a thread-specific storage destructor. The
477 function will be called when the current thread calls @code{thrd_exit}
478 (but never when calling @code{tss_delete} or @code{exit}).
481 @defvr Macro thread_local
482 @standards{C11, threads.h}
483 @code{thread_local} is used to mark a variable with thread storage
484 duration, which means it is created when the thread starts and cleaned
485 up when the thread ends.
487 @emph{Note:} For C++, C++11 or later is required to use the
488 @code{thread_local} keyword.
491 @defvr Macro TSS_DTOR_ITERATIONS
492 @standards{C11, threads.h}
493 @code{TSS_DTOR_ITERATIONS} is an integer constant expression
494 representing the maximum number of iterations over all thread-local
495 destructors at the time of thread termination. This value provides a
496 bounded limit to the destruction of thread-local storage; e.g.,
497 consider a destructor that creates more thread-local storage.
500 The following functions are used to manage thread-local storage:
502 @deftypefun int tss_create (tss_t *@var{tss_key}, tss_dtor_t @var{destructor})
503 @standards{C11, threads.h}
504 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
505 @code{tss_create} creates a new thread-specific storage key and stores
506 it in the object pointed to by @var{tss_key}. Although the same key
507 value may be used by different threads, the values bound to the key by
508 @code{tss_set} are maintained on a per-thread basis and persist for
509 the life of the calling thread.
511 If @code{destructor} is not NULL, a destructor function will be set,
512 and called when the thread finishes its execution by calling
515 This function returns @code{thrd_success} if @code{tss_key} is
516 successfully set to a unique value for the thread; otherwise,
517 @code{thrd_error} is returned and the value of @code{tss_key} is
521 @deftypefun int tss_set (tss_t @var{tss_key}, void *@var{val})
522 @standards{C11, threads.h}
523 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
524 @code{tss_set} sets the value of the thread-specific storage
525 identified by @var{tss_key} for the current thread to @var{val}.
526 Different threads may set different values to the same key.
528 This function returns either @code{thrd_success} or @code{thrd_error}.
531 @deftypefun {void *} tss_get (tss_t @var{tss_key})
532 @standards{C11, threads.h}
533 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
534 @code{tss_get} returns the value identified by @var{tss_key} held in
535 thread-specific storage for the current thread. Different threads may
536 get different values identified by the same key. On failure,
537 @code{tss_get} returns zero.
540 @deftypefun void tss_delete (tss_t @var{tss_key})
541 @standards{C11, threads.h}
542 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
543 @code{tss_delete} destroys the thread-specific storage identified by
549 @section POSIX Threads
552 This section describes the @glibcadj{} POSIX Threads implementation.
555 * Thread-specific Data:: Support for creating and
556 managing thread-specific data
557 * Non-POSIX Extensions:: Additional functions to extend
558 POSIX Thread functionality
561 @node Thread-specific Data
562 @subsection Thread-specific Data
564 The @glibcadj{} implements functions to allow users to create and manage
565 data specific to a thread. Such data may be destroyed at thread exit,
566 if a destructor is provided. The following functions are defined:
568 @deftypefun int pthread_key_create (pthread_key_t *@var{key}, void (*@var{destructor})(void*))
569 @standards{POSIX, pthread.h}
570 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
571 @c pthread_key_create ok
574 Create a thread-specific data key for the calling thread, referenced by
577 Objects declared with the C++11 @code{thread_local} keyword are destroyed
578 before thread-specific data, so they should not be used in thread-specific
579 data destructors or even as members of the thread-specific data, since the
580 latter is passed as an argument to the destructor function.
583 @deftypefun int pthread_key_delete (pthread_key_t @var{key})
584 @standards{POSIX, pthread.h}
585 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
586 @c pthread_key_delete ok
587 @c This uses atomic compare and exchange to increment the seq number
588 @c after testing it's not a KEY_UNUSED seq number.
590 Destroy the thread-specific data @var{key} in the calling thread. The
591 destructor for the thread-specific data is not called during destruction, nor
592 is it called during thread exit.
595 @deftypefun void *pthread_getspecific (pthread_key_t @var{key})
596 @standards{POSIX, pthread.h}
597 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
598 @c pthread_getspecific ok
599 Return the thread-specific data associated with @var{key} in the calling
603 @deftypefun int pthread_setspecific (pthread_key_t @var{key}, const void *@var{value})
604 @standards{POSIX, pthread.h}
605 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
606 @c pthread_setspecific @asucorrupt @ascuheap @acucorrupt @acsmem
607 @c a level2 block may be allocated by a signal handler after
608 @c another call already made a decision to allocate it, thus losing
609 @c the allocated value. the seq number is updated before the
610 @c value, which might cause an earlier-generation value to seem
611 @c current if setspecific is cancelled or interrupted by a signal
613 @c calloc dup @ascuheap @acsmem
614 Associate the thread-specific @var{value} with @var{key} in the calling thread.
618 @node Non-POSIX Extensions
619 @subsection Non-POSIX Extensions
621 In addition to implementing the POSIX API for threads, @theglibc{} provides
622 additional functions and interfaces to provide functionality not specified in
626 * Default Thread Attributes:: Setting default attributes for
627 threads in a process.
628 * Initial Thread Signal Mask:: Setting the initial mask of threads.
629 * Waiting with Explicit Clocks:: Functions for waiting with an
630 explicit clock specification.
631 * Single-Threaded:: Detecting single-threaded execution.
632 * Restartable Sequences:: Linux-specific restartable sequences
636 @node Default Thread Attributes
637 @subsubsection Setting Process-wide defaults for thread attributes
639 @Theglibc{} provides non-standard API functions to set and get the default
640 attributes used in the creation of threads in a process.
642 @deftypefun int pthread_getattr_default_np (pthread_attr_t *@var{attr})
643 @standards{GNU, pthread.h}
644 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
645 @c Takes lock around read from default_pthread_attr.
646 Get the default attribute values and set @var{attr} to match. This
647 function returns @math{0} on success and a non-zero error code on
651 @deftypefun int pthread_setattr_default_np (pthread_attr_t *@var{attr})
652 @standards{GNU, pthread.h}
653 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{}}}
654 @c pthread_setattr_default_np @ascuheap @asulock @aculock @acsmem
655 @c check_sched_policy_attr ok
656 @c check_sched_priority_attr ok
657 @c sched_get_priority_min dup ok
658 @c sched_get_priority_max dup ok
659 @c check_stacksize_attr ok
660 @c lll_lock @asulock @aculock
661 @c free dup @ascuheap @acsmem
662 @c realloc dup @ascuheap @acsmem
664 @c lll_unlock @asulock @aculock
665 Set the default attribute values to match the values in @var{attr}. The
666 function returns @math{0} on success and a non-zero error code on failure.
667 The following error codes are defined for this function:
671 At least one of the values in @var{attr} does not qualify as valid for the
672 attributes or the stack address is set in the attribute.
674 The system does not have sufficient memory.
678 @node Initial Thread Signal Mask
679 @subsubsection Controlling the Initial Signal Mask of a New Thread
681 @Theglibc{} provides a way to specify the initial signal mask of a
682 thread created using @code{pthread_create}, passing a thread attribute
683 object configured for this purpose.
685 @deftypefun int pthread_attr_setsigmask_np (pthread_attr_t *@var{attr}, const sigset_t *@var{sigmask})
686 @standards{GNU, pthread.h}
687 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
688 Change the initial signal mask specified by @var{attr}. If
689 @var{sigmask} is not @code{NULL}, the initial signal mask for new
690 threads created with @var{attr} is set to @code{*@var{sigmask}}. If
691 @var{sigmask} is @code{NULL}, @var{attr} will no longer specify an
692 explicit signal mask, so that the initial signal mask of the new
693 thread is inherited from the thread that calls @code{pthread_create}.
695 This function returns zero on success, and @code{ENOMEM} on memory
699 @deftypefun int pthread_attr_getsigmask_np (const pthread_attr_t *@var{attr}, sigset_t *@var{sigmask})
700 @standards{GNU, pthread.h}
701 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
702 Retrieve the signal mask stored in @var{attr} and copy it to
703 @code{*@var{sigmask}}. If the signal mask has not been set, return
704 the special constant @code{PTHREAD_ATTR_NO_SIGMASK_NP}, otherwise
707 @c Move this to the documentation of pthread_getattr_np once it exists.
708 Obtaining the signal mask only works if it has been previously stored
709 by @code{pthread_attr_setsigmask_np}. For example, the
710 @code{pthread_getattr_np} function does not obtain the current signal
711 mask of the specified thread, and @code{pthread_attr_getsigmask_np}
712 will subsequently report the signal mask as unset.
715 @deftypevr Macro int PTHREAD_ATTR_NO_SIGMASK_NP
716 The special value returned by @code{pthread_attr_setsigmask_np} to
717 indicate that no signal mask has been set for the attribute.
720 It is possible to create a new thread with a specific signal mask
721 without using these functions. On the thread that calls
722 @code{pthread_create}, the required steps for the general case are:
726 Mask all signals, and save the old signal mask, using
727 @code{pthread_sigmask}. This ensures that the new thread will be
728 created with all signals masked, so that no signals can be delivered
729 to the thread until the desired signal mask is set.
732 Call @code{pthread_create} to create the new thread, passing the
733 desired signal mask to the thread start routine (which could be a
734 wrapper function for the actual thread start routine). It may be
735 necessary to make a copy of the desired signal mask on the heap, so
736 that the life-time of the copy extends to the point when the start
737 routine needs to access the signal mask.
740 Restore the thread's signal mask, to the set that was saved in the
744 The start routine for the created thread needs to locate the desired
745 signal mask and use @code{pthread_sigmask} to apply it to the thread.
746 If the signal mask was copied to a heap allocation, the copy should be
749 @node Waiting with Explicit Clocks
750 @subsubsection Functions for Waiting According to a Specific Clock
752 @Theglibc{} provides several waiting functions that expect an explicit
753 @code{clockid_t} argument.
756 @comment POSIX-proposed
757 @deftypefun int sem_clockwait (sem_t *@var{sem}, clockid_t @var{clockid}, const struct timespec *@var{abstime})
758 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
759 Behaves like @code{sem_timedwait} except the time @var{abstime} is measured
760 against the clock specified by @var{clockid} rather than
761 @code{CLOCK_REALTIME}. Currently, @var{clockid} must be either
762 @code{CLOCK_MONOTONIC} or @code{CLOCK_REALTIME}.
766 @comment POSIX-proposed
767 @deftypefun int pthread_cond_clockwait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}, clockid_t @var{clockid}, const struct timespec *@var{abstime})
768 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
769 @c If exactly the same function with arguments is called from a signal
770 @c handler that interrupts between the mutex unlock and sleep then it
771 @c will unlock the mutex twice resulting in undefined behaviour. Keep
772 @c in mind that the unlock and sleep are only atomic with respect to other
773 @c threads (really a happens-after relationship for pthread_cond_broadcast
774 @c and pthread_cond_signal).
775 @c In the AC case we would cancel the thread and the mutex would remain
776 @c locked and we can't recover from that.
777 Behaves like @code{pthread_cond_timedwait} except the time @var{abstime} is
778 measured against the clock specified by @var{clockid} rather than the clock
779 specified or defaulted when @code{pthread_cond_init} was called. Currently,
780 @var{clockid} must be either @code{CLOCK_MONOTONIC} or
781 @code{CLOCK_REALTIME}.
785 @comment POSIX-proposed
786 @deftypefun int pthread_rwlock_clockrdlock (pthread_rwlock_t *@var{rwlock}, clockid_t @var{clockid}, const struct timespec *@var{abstime})
787 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
788 Behaves like @code{pthread_rwlock_timedrdlock} except the time
789 @var{abstime} is measured against the clock specified by @var{clockid}
790 rather than @code{CLOCK_REALTIME}. Currently, @var{clockid} must be either
791 @code{CLOCK_MONOTONIC} or @code{CLOCK_REALTIME}, otherwise @code{EINVAL} is
796 @comment POSIX-proposed
797 @deftypefun int pthread_rwlock_clockwrlock (pthread_rwlock_t *@var{rwlock}, clockid_t @var{clockid}, const struct timespec *@var{abstime})
798 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
799 Behaves like @code{pthread_rwlock_timedwrlock} except the time
800 @var{abstime} is measured against the clock specified by @var{clockid}
801 rather than @code{CLOCK_REALTIME}. Currently, @var{clockid} must be either
802 @code{CLOCK_MONOTONIC} or @code{CLOCK_REALTIME}, otherwise @code{EINVAL} is
807 @comment GNU extension
808 @deftypefun int pthread_tryjoin_np (pthread_t *@var{thread}, void **@var{thread_return})
809 @standards{GNU, pthread.h}
810 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
811 Behaves like @code{pthread_join} except that it will return @code{EBUSY}
812 immediately if the thread specified by @var{thread} has not yet terminated.
816 @comment GNU extension
817 @deftypefun int pthread_timedjoin_np (pthread_t *@var{thread}, void **@var{thread_return}, const struct timespec *@var{abstime})
818 @standards{GNU, pthread.h}
819 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
820 Behaves like @code{pthread_tryjoin_np} except that it will block until the
821 absolute time @var{abstime} measured against @code{CLOCK_REALTIME} is
822 reached if the thread has not terminated by that time and return
823 @code{EBUSY}. If @var{abstime} is equal to @code{NULL} then the function
824 will wait forever in the same way as @code{pthread_join}.
828 @comment GNU extension
829 @deftypefun int pthread_clockjoin_np (pthread_t *@var{thread}, void **@var{thread_return}, clockid_t @var{clockid}, const struct timespec *@var{abstime})
830 @standards{GNU, pthread.h}
831 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
832 Behaves like @code{pthread_timedjoin_np} except that the absolute time in
833 @var{abstime} is measured against the clock specified by @var{clockid}.
834 Currently, @var{clockid} must be either @code{CLOCK_MONOTONIC} or
835 @code{CLOCK_REALTIME}.
838 @node Single-Threaded
839 @subsubsection Detecting Single-Threaded Execution
841 Multi-threaded programs require synchronization among threads. This
842 synchronization can be costly even if there is just a single thread
843 and no data is shared between multiple processors. @Theglibc{} offers
844 an interface to detect whether the process is in single-threaded mode.
845 Applications can use this information to avoid synchronization, for
846 example by using regular instructions to load and store memory instead
847 of atomic instructions, or using relaxed memory ordering instead of
848 stronger memory ordering.
850 @deftypevar char __libc_single_threaded
851 @standards{GNU, sys/single_threaded.h}
852 This variable is non-zero if the current process is definitely
853 single-threaded. If it is zero, the process may be multi-threaded,
854 or @theglibc{} cannot determine at this point of the program execution
855 whether the process is single-threaded or not.
857 Applications must never write to this variable.
860 Most applications should perform the same actions whether or not
861 @code{__libc_single_threaded} is true, except with less
862 synchronization. If this rule is followed, a process that
863 subsequently becomes multi-threaded is already in a consistent state.
864 For example, in order to increment a reference count, the following
868 if (__libc_single_threaded)
869 atomic_fetch_add (&reference_count, 1, memory_order_relaxed);
871 atomic_fetch_add (&reference_count, 1, memory_order_acq_rel);
874 @c Note: No memory order on __libc_single_threaded. The
875 @c implementation must ensure that exit of the critical
876 @c (second-to-last) thread happens-before setting
877 @c __libc_single_threaded to true. Otherwise, acquire MO might be
878 @c needed for reading the variable in some scenarios, and that would
879 @c completely defeat its purpose.
881 This still requires some form of synchronization on the
882 single-threaded branch, so it can be beneficial not to declare the
883 reference count as @code{_Atomic}, and use the GCC @code{__atomic}
884 built-ins. @xref{__atomic Builtins,, Built-in Functions for Memory
885 Model Aware Atomic Operations, gcc, Using the GNU Compiler Collection
886 (GCC)}. Then the code to increment a reference count looks like this:
889 if (__libc_single_threaded)
892 __atomic_fetch_add (&reference_count, 1, __ATOMIC_ACQ_REL);
895 (Depending on the data associated with the reference count, it may be
896 possible to use the weaker @code{__ATOMIC_RELAXED} memory ordering on
897 the multi-threaded branch.)
899 Several functions in @theglibc{} can change the value of the
900 @code{__libc_single_threaded} variable. For example, creating new
901 threads using the @code{pthread_create} or @code{thrd_create} function
902 sets the variable to false. This can also happen indirectly, say via
903 a call to @code{dlopen}. Therefore, applications need to make a copy
904 of the value of @code{__libc_single_threaded} if after such a function
905 call, behavior must match the value as it was before the call, like
909 bool single_threaded = __libc_single_threaded;
911 prepare_single_threaded ();
913 prepare_multi_thread ();
915 void *handle = dlopen (shared_library_name, RTLD_NOW);
916 lookup_symbols (handle);
919 cleanup_single_threaded ();
921 cleanup_multi_thread ();
924 Since the value of @code{__libc_single_threaded} can change from true
925 to false during the execution of the program, it is not useful for
926 selecting optimized function implementations in IFUNC resolvers.
928 Atomic operations can also be used on mappings shared among
929 single-threaded processes. This means that a compiler must not use
930 @code{__libc_single_threaded} to optimize atomic operations, unless it
931 is able to prove that the memory is not shared.
933 @strong{Implementation Note:} The @code{__libc_single_threaded}
934 variable is not declared as @code{volatile} because it is expected
935 that compilers optimize a sequence of single-threaded checks into one
936 check, for example if several reference counts are updated. The
937 current implementation in @theglibc{} does not set the
938 @code{__libc_single_threaded} variable to a true value if a process
939 turns single-threaded again. Future versions of @theglibc{} may do
940 this, but only as the result of function calls which imply an acquire
941 (compiler) barrier. (Some compilers assume that well-known functions
942 such as @code{malloc} do not write to global variables, and setting
943 @code{__libc_single_threaded} would introduce a data race and
944 undefined behavior.) In any case, an application must not write to
945 @code{__libc_single_threaded} even if it has joined the last
946 application-created thread because future versions of @theglibc{} may
947 create background threads after the first thread has been created, and
948 the application has no way of knowing that these threads are present.
950 @node Restartable Sequences
951 @subsubsection Restartable Sequences
953 This section describes restartable sequences integration for
954 @theglibc{}. This functionality is only available on Linux.
956 @deftp {Data Type} {struct rseq}
957 @standards{Linux, sys/rseq.h}
958 The type of the restartable sequences area. Future versions
959 of Linux may add additional fields to the end of this structure.
962 Users need to obtain the address of the restartable sequences area using
963 the thread pointer and the @code{__rseq_offset} variable, described
966 One use of the restartable sequences area is to read the current CPU
967 number from its @code{cpu_id} field, as an inline version of
968 @code{sched_getcpu}. @Theglibc{} sets the @code{cpu_id} field to
969 @code{RSEQ_CPU_ID_REGISTRATION_FAILED} if registration failed or was
972 Furthermore, users can store the address of a @code{struct rseq_cs}
973 object into the @code{rseq_cs} field of @code{struct rseq}, thus
974 informing the kernel that the thread enters a restartable sequence
975 critical section. This pointer and the code areas it itself points to
976 must not be left pointing to memory areas which are freed or re-used.
977 Several approaches can guarantee this. If the application or library
978 can guarantee that the memory used to hold the @code{struct rseq_cs} and
979 the code areas it refers to are never freed or re-used, no special
980 action must be taken. Else, before that memory is re-used of freed, the
981 application is responsible for setting the @code{rseq_cs} field to
982 @code{NULL} in each thread's restartable sequence area to guarantee that
983 it does not leak dangling references. Because the application does not
984 typically have knowledge of libraries' use of restartable sequences, it
985 is recommended that libraries using restartable sequences which may end
986 up freeing or re-using their memory set the @code{rseq_cs} field to
987 @code{NULL} before returning from library functions which use
988 restartable sequences.
990 The manual for the @code{rseq} system call can be found
991 at @uref{https://git.kernel.org/pub/scm/libs/librseq/librseq.git/tree/doc/man/rseq.2}.
994 @deftypevar {ptrdiff_t} __rseq_offset
995 @standards{Linux, sys/rseq.h}
996 This variable contains the offset between the thread pointer (as defined
997 by @code{__builtin_thread_pointer} or the thread pointer register for
998 the architecture) and the restartable sequences area. This value is the
999 same for all threads in the process. If the restartable sequences area
1000 is located at a lower address than the location to which the thread
1001 pointer points, the value is negative.
1004 @deftypevar {unsigned int} __rseq_size
1005 @standards{Linux, sys/rseq.h}
1006 This variable is either zero (if restartable sequence registration
1007 failed or has been disabled) or the size of the restartable sequence
1008 registration. This can be different from the size of @code{struct rseq}
1009 if the kernel has extended the size of the registration. If
1010 registration is successful, @code{__rseq_size} is at least 32 (the
1011 initial size of @code{struct rseq}).
1014 @deftypevar {unsigned int} __rseq_flags
1015 @standards{Linux, sys/rseq.h}
1016 The flags used during restartable sequence registration with the kernel.
1020 @deftypevr Macro int RSEQ_SIG
1021 @standards{Linux, sys/rseq.h}
1022 Each supported architecture provides a @code{RSEQ_SIG} macro in
1023 @file{sys/rseq.h} which contains a signature. That signature is
1024 expected to be present in the code before each restartable sequences
1025 abort handler. Failure to provide the expected signature may terminate
1026 the process with a segmentation fault.
1029 @c FIXME these are undocumented:
1031 @c pthread_attr_destroy
1032 @c pthread_attr_getaffinity_np
1033 @c pthread_attr_getdetachstate
1034 @c pthread_attr_getguardsize
1035 @c pthread_attr_getinheritsched
1036 @c pthread_attr_getschedparam
1037 @c pthread_attr_getschedpolicy
1038 @c pthread_attr_getscope
1039 @c pthread_attr_getstack
1040 @c pthread_attr_getstackaddr
1041 @c pthread_attr_getstacksize
1042 @c pthread_attr_init
1043 @c pthread_attr_setaffinity_np
1044 @c pthread_attr_setdetachstate
1045 @c pthread_attr_setguardsize
1046 @c pthread_attr_setinheritsched
1047 @c pthread_attr_setschedparam
1048 @c pthread_attr_setschedpolicy
1049 @c pthread_attr_setscope
1050 @c pthread_attr_setstack
1051 @c pthread_attr_setstackaddr
1052 @c pthread_attr_setstacksize
1053 @c pthread_barrierattr_destroy
1054 @c pthread_barrierattr_getpshared
1055 @c pthread_barrierattr_init
1056 @c pthread_barrierattr_setpshared
1057 @c pthread_barrier_destroy
1058 @c pthread_barrier_init
1059 @c pthread_barrier_wait
1061 @c pthread_cleanup_push
1062 @c pthread_cleanup_pop
1063 @c pthread_condattr_destroy
1064 @c pthread_condattr_getclock
1065 @c pthread_condattr_getpshared
1066 @c pthread_condattr_init
1067 @c pthread_condattr_setclock
1068 @c pthread_condattr_setpshared
1069 @c pthread_cond_broadcast
1070 @c pthread_cond_destroy
1071 @c pthread_cond_init
1072 @c pthread_cond_signal
1073 @c pthread_cond_timedwait
1074 @c pthread_cond_wait
1079 @c pthread_getaffinity_np
1080 @c pthread_getattr_np
1081 @c pthread_getconcurrency
1082 @c pthread_getcpuclockid
1083 @c pthread_getname_np
1084 @c pthread_getschedparam
1087 @c pthread_kill_other_threads_np
1088 @c pthread_mutexattr_destroy
1089 @c pthread_mutexattr_getkind_np
1090 @c pthread_mutexattr_getprioceiling
1091 @c pthread_mutexattr_getprotocol
1092 @c pthread_mutexattr_getpshared
1093 @c pthread_mutexattr_getrobust
1094 @c pthread_mutexattr_getrobust_np
1095 @c pthread_mutexattr_gettype
1096 @c pthread_mutexattr_init
1097 @c pthread_mutexattr_setkind_np
1098 @c pthread_mutexattr_setprioceiling
1099 @c pthread_mutexattr_setprotocol
1100 @c pthread_mutexattr_setpshared
1101 @c pthread_mutexattr_setrobust
1102 @c pthread_mutexattr_setrobust_np
1103 @c pthread_mutexattr_settype
1104 @c pthread_mutex_consistent
1105 @c pthread_mutex_consistent_np
1106 @c pthread_mutex_destroy
1107 @c pthread_mutex_getprioceiling
1108 @c pthread_mutex_init
1109 @c pthread_mutex_lock
1110 @c pthread_mutex_setprioceiling
1111 @c pthread_mutex_timedlock
1112 @c pthread_mutex_trylock
1113 @c pthread_mutex_unlock
1115 @c pthread_rwlockattr_destroy
1116 @c pthread_rwlockattr_getkind_np
1117 @c pthread_rwlockattr_getpshared
1118 @c pthread_rwlockattr_init
1119 @c pthread_rwlockattr_setkind_np
1120 @c pthread_rwlockattr_setpshared
1121 @c pthread_rwlock_destroy
1122 @c pthread_rwlock_init
1123 @c pthread_rwlock_rdlock
1124 @c pthread_rwlock_timedrdlock
1125 @c pthread_rwlock_timedwrlock
1126 @c pthread_rwlock_tryrdlock
1127 @c pthread_rwlock_trywrlock
1128 @c pthread_rwlock_unlock
1129 @c pthread_rwlock_wrlock
1131 @c pthread_setaffinity_np
1132 @c pthread_setcancelstate
1133 @c pthread_setcanceltype
1134 @c pthread_setconcurrency
1135 @c pthread_setname_np
1136 @c pthread_setschedparam
1137 @c pthread_setschedprio
1140 @c pthread_spin_destroy
1141 @c pthread_spin_init
1142 @c pthread_spin_lock
1143 @c pthread_spin_trylock
1144 @c pthread_spin_unlock
1145 @c pthread_testcancel