linuxthreads.texi 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. @node POSIX Threads
  2. @c @node POSIX Threads, , Top, Top
  3. @chapter POSIX Threads
  4. @c %MENU% The standard threads library
  5. @c This chapter needs more work bigtime. -zw
  6. This chapter describes the pthreads (POSIX threads) library. This
  7. library provides support functions for multithreaded programs: thread
  8. primitives, synchronization objects, and so forth. It also implements
  9. POSIX 1003.1b semaphores (not to be confused with System V semaphores).
  10. The threads operations (@samp{pthread_*}) do not use @var{errno}.
  11. Instead they return an error code directly. The semaphore operations do
  12. use @var{errno}.
  13. @menu
  14. * Basic Thread Operations:: Creating, terminating, and waiting for threads.
  15. * Thread Attributes:: Tuning thread scheduling.
  16. * Cancellation:: Stopping a thread before it's done.
  17. * Cleanup Handlers:: Deallocating resources when a thread is
  18. cancelled.
  19. * Mutexes:: One way to synchronize threads.
  20. * Condition Variables:: Another way.
  21. * POSIX Semaphores:: And a third way.
  22. * Thread-Specific Data:: Variables with different values in
  23. different threads.
  24. * Threads and Signal Handling:: Why you should avoid mixing the two, and
  25. how to do it if you must.
  26. * Miscellaneous Thread Functions:: A grab bag of utility routines.
  27. @end menu
  28. @node Basic Thread Operations
  29. @section Basic Thread Operations
  30. These functions are the thread equivalents of @code{fork}, @code{exit},
  31. and @code{wait}.
  32. @comment pthread.h
  33. @comment POSIX
  34. @deftypefun int pthread_create (pthread_t * @var{thread}, pthread_attr_t * @var{attr}, void * (*@var{start_routine})(void *), void * @var{arg})
  35. @code{pthread_create} creates a new thread of control that executes
  36. concurrently with the calling thread. The new thread calls the
  37. function @var{start_routine}, passing it @var{arg} as first argument. The
  38. new thread terminates either explicitly, by calling @code{pthread_exit},
  39. or implicitly, by returning from the @var{start_routine} function. The
  40. latter case is equivalent to calling @code{pthread_exit} with the result
  41. returned by @var{start_routine} as exit code.
  42. The @var{attr} argument specifies thread attributes to be applied to the
  43. new thread. @xref{Thread Attributes}, for details. The @var{attr}
  44. argument can also be @code{NULL}, in which case default attributes are
  45. used: the created thread is joinable (not detached) and has an ordinary
  46. (not realtime) scheduling policy.
  47. On success, the identifier of the newly created thread is stored in the
  48. location pointed by the @var{thread} argument, and a 0 is returned. On
  49. error, a non-zero error code is returned.
  50. This function may return the following errors:
  51. @table @code
  52. @item EAGAIN
  53. Not enough system resources to create a process for the new thread,
  54. or more than @code{PTHREAD_THREADS_MAX} threads are already active.
  55. @end table
  56. @end deftypefun
  57. @comment pthread.h
  58. @comment POSIX
  59. @deftypefun void pthread_exit (void *@var{retval})
  60. @code{pthread_exit} terminates the execution of the calling thread. All
  61. cleanup handlers (@pxref{Cleanup Handlers}) that have been set for the
  62. calling thread with @code{pthread_cleanup_push} are executed in reverse
  63. order (the most recently pushed handler is executed first). Finalization
  64. functions for thread-specific data are then called for all keys that
  65. have non-@code{NULL} values associated with them in the calling thread
  66. (@pxref{Thread-Specific Data}). Finally, execution of the calling
  67. thread is stopped.
  68. The @var{retval} argument is the return value of the thread. It can be
  69. retrieved from another thread using @code{pthread_join}.
  70. The @code{pthread_exit} function never returns.
  71. @end deftypefun
  72. @comment pthread.h
  73. @comment POSIX
  74. @deftypefun int pthread_cancel (pthread_t @var{thread})
  75. @code{pthread_cancel} sends a cancellation request to the thread denoted
  76. by the @var{thread} argument. If there is no such thread,
  77. @code{pthread_cancel} fails and returns @code{ESRCH}. Otherwise it
  78. returns 0. @xref{Cancellation}, for details.
  79. @end deftypefun
  80. @comment pthread.h
  81. @comment POSIX
  82. @deftypefun int pthread_join (pthread_t @var{th}, void **thread_@var{return})
  83. @code{pthread_join} suspends the execution of the calling thread until
  84. the thread identified by @var{th} terminates, either by calling
  85. @code{pthread_exit} or by being cancelled.
  86. If @var{thread_return} is not @code{NULL}, the return value of @var{th}
  87. is stored in the location pointed to by @var{thread_return}. The return
  88. value of @var{th} is either the argument it gave to @code{pthread_exit},
  89. or @code{PTHREAD_CANCELED} if @var{th} was cancelled.
  90. The joined thread @code{th} must be in the joinable state: it must not
  91. have been detached using @code{pthread_detach} or the
  92. @code{PTHREAD_CREATE_DETACHED} attribute to @code{pthread_create}.
  93. When a joinable thread terminates, its memory resources (thread
  94. descriptor and stack) are not deallocated until another thread performs
  95. @code{pthread_join} on it. Therefore, @code{pthread_join} must be called
  96. once for each joinable thread created to avoid memory leaks.
  97. At most one thread can wait for the termination of a given
  98. thread. Calling @code{pthread_join} on a thread @var{th} on which
  99. another thread is already waiting for termination returns an error.
  100. @code{pthread_join} is a cancellation point. If a thread is canceled
  101. while suspended in @code{pthread_join}, the thread execution resumes
  102. immediately and the cancellation is executed without waiting for the
  103. @var{th} thread to terminate. If cancellation occurs during
  104. @code{pthread_join}, the @var{th} thread remains not joined.
  105. On success, the return value of @var{th} is stored in the location
  106. pointed to by @var{thread_return}, and 0 is returned. On error, one of
  107. the following values is returned:
  108. @table @code
  109. @item ESRCH
  110. No thread could be found corresponding to that specified by @var{th}.
  111. @item EINVAL
  112. The @var{th} thread has been detached, or another thread is already
  113. waiting on termination of @var{th}.
  114. @item EDEADLK
  115. The @var{th} argument refers to the calling thread.
  116. @end table
  117. @end deftypefun
  118. @node Thread Attributes
  119. @section Thread Attributes
  120. @comment pthread.h
  121. @comment POSIX
  122. Threads have a number of attributes that may be set at creation time.
  123. This is done by filling a thread attribute object @var{attr} of type
  124. @code{pthread_attr_t}, then passing it as second argument to
  125. @code{pthread_create}. Passing @code{NULL} is equivalent to passing a
  126. thread attribute object with all attributes set to their default values.
  127. Attribute objects are consulted only when creating a new thread. The
  128. same attribute object can be used for creating several threads.
  129. Modifying an attribute object after a call to @code{pthread_create} does
  130. not change the attributes of the thread previously created.
  131. @comment pthread.h
  132. @comment POSIX
  133. @deftypefun int pthread_attr_init (pthread_attr_t *@var{attr})
  134. @code{pthread_attr_init} initializes the thread attribute object
  135. @var{attr} and fills it with default values for the attributes. (The
  136. default values are listed below for each attribute.)
  137. Each attribute @var{attrname} (see below for a list of all attributes)
  138. can be individually set using the function
  139. @code{pthread_attr_set@var{attrname}} and retrieved using the function
  140. @code{pthread_attr_get@var{attrname}}.
  141. @end deftypefun
  142. @comment pthread.h
  143. @comment POSIX
  144. @deftypefun int pthread_attr_destroy (pthread_attr_t *@var{attr})
  145. @code{pthread_attr_destroy} destroys the attribute object pointed to by
  146. @var{attr} releasing any resources associated with it. @var{attr} is
  147. left in an undefined state, and you must not use it again in a call to
  148. any pthreads function until it has been reinitialized.
  149. @end deftypefun
  150. @findex pthread_attr_setinheritsched
  151. @findex pthread_attr_setschedparam
  152. @findex pthread_attr_setschedpolicy
  153. @findex pthread_attr_setscope
  154. @comment pthread.h
  155. @comment POSIX
  156. @deftypefun int pthread_attr_set@var{attr} (pthread_attr_t *@var{obj}, int @var{value})
  157. Set attribute @var{attr} to @var{value} in the attribute object pointed
  158. to by @var{obj}. See below for a list of possible attributes and the
  159. values they can take.
  160. On success, these functions return 0. If @var{value} is not meaningful
  161. for the @var{attr} being modified, they will return the error code
  162. @code{EINVAL}. Some of the functions have other failure modes; see
  163. below.
  164. @end deftypefun
  165. @findex pthread_attr_getinheritsched
  166. @findex pthread_attr_getschedparam
  167. @findex pthread_attr_getschedpolicy
  168. @findex pthread_attr_getscope
  169. @comment pthread.h
  170. @comment POSIX
  171. @deftypefun int pthread_attr_get@var{attr} (const pthread_attr_t *@var{obj}, int *@var{value})
  172. Store the current setting of @var{attr} in @var{obj} into the variable
  173. pointed to by @var{value}.
  174. These functions always return 0.
  175. @end deftypefun
  176. The following thread attributes are supported:
  177. @table @samp
  178. @item detachstate
  179. Choose whether the thread is created in the joinable state (value
  180. @code{PTHREAD_CREATE_JOINABLE}) or in the detached state
  181. (@code{PTHREAD_CREATE_DETACHED}). The default is
  182. @code{PTHREAD_CREATE_JOINABLE}.
  183. In the joinable state, another thread can synchronize on the thread
  184. termination and recover its termination code using @code{pthread_join},
  185. but some of the thread resources are kept allocated after the thread
  186. terminates, and reclaimed only when another thread performs
  187. @code{pthread_join} on that thread.
  188. In the detached state, the thread resources are immediately freed when
  189. it terminates, but @code{pthread_join} cannot be used to synchronize on
  190. the thread termination.
  191. A thread created in the joinable state can later be put in the detached
  192. thread using @code{pthread_detach}.
  193. @item schedpolicy
  194. Select the scheduling policy for the thread: one of @code{SCHED_OTHER}
  195. (regular, non-realtime scheduling), @code{SCHED_RR} (realtime,
  196. round-robin) or @code{SCHED_FIFO} (realtime, first-in first-out).
  197. The default is @code{SCHED_OTHER}.
  198. @c Not doc'd in our manual: FIXME.
  199. @c See @code{sched_setpolicy} for more information on scheduling policies.
  200. The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
  201. are available only to processes with superuser privileges.
  202. @code{pthread_attr_setschedparam} will fail and return @code{ENOTSUP} if
  203. you try to set a realtime policy when you are unprivileged.
  204. The scheduling policy of a thread can be changed after creation with
  205. @code{pthread_setschedparam}.
  206. @item schedparam
  207. Change the scheduling parameter (the scheduling priority)
  208. for the thread. The default is 0.
  209. This attribute is not significant if the scheduling policy is
  210. @code{SCHED_OTHER}; it only matters for the realtime policies
  211. @code{SCHED_RR} and @code{SCHED_FIFO}.
  212. The scheduling priority of a thread can be changed after creation with
  213. @code{pthread_setschedparam}.
  214. @item inheritsched
  215. Choose whether the scheduling policy and scheduling parameter for the
  216. newly created thread are determined by the values of the
  217. @var{schedpolicy} and @var{schedparam} attributes (value
  218. @code{PTHREAD_EXPLICIT_SCHED}) or are inherited from the parent thread
  219. (value @code{PTHREAD_INHERIT_SCHED}). The default is
  220. @code{PTHREAD_EXPLICIT_SCHED}.
  221. @item scope
  222. Choose the scheduling contention scope for the created thread. The
  223. default is @code{PTHREAD_SCOPE_SYSTEM}, meaning that the threads contend
  224. for CPU time with all processes running on the machine. In particular,
  225. thread priorities are interpreted relative to the priorities of all
  226. other processes on the machine. The other possibility,
  227. @code{PTHREAD_SCOPE_PROCESS}, means that scheduling contention occurs
  228. only between the threads of the running process: thread priorities are
  229. interpreted relative to the priorities of the other threads of the
  230. process, regardless of the priorities of other processes.
  231. @code{PTHREAD_SCOPE_PROCESS} is not supported in LinuxThreads. If you
  232. try to set the scope to this value @code{pthread_attr_setscope} will
  233. fail and return @code{ENOTSUP}.
  234. @end table
  235. @node Cancellation
  236. @section Cancellation
  237. Cancellation is the mechanism by which a thread can terminate the
  238. execution of another thread. More precisely, a thread can send a
  239. cancellation request to another thread. Depending on its settings, the
  240. target thread can then either ignore the request, honor it immediately,
  241. or defer it till it reaches a cancellation point. When threads are
  242. first created by @code{pthread_create}, they always defer cancellation
  243. requests.
  244. When a thread eventually honors a cancellation request, it behaves as if
  245. @code{pthread_exit(PTHREAD_CANCELED)} was called. All cleanup handlers
  246. are executed in reverse order, finalization functions for
  247. thread-specific data are called, and finally the thread stops executing.
  248. If the cancelled thread was joinable, the return value
  249. @code{PTHREAD_CANCELED} is provided to whichever thread calls
  250. @var{pthread_join} on it. See @code{pthread_exit} for more information.
  251. Cancellation points are the points where the thread checks for pending
  252. cancellation requests and performs them. The POSIX threads functions
  253. @code{pthread_join}, @code{pthread_cond_wait},
  254. @code{pthread_cond_timedwait}, @code{pthread_testcancel},
  255. @code{sem_wait}, and @code{sigwait} are cancellation points. In
  256. addition, these system calls are cancellation points:
  257. @multitable @columnfractions .33 .33 .33
  258. @item @t{accept} @tab @t{open} @tab @t{sendmsg}
  259. @item @t{close} @tab @t{pause} @tab @t{sendto}
  260. @item @t{connect} @tab @t{read} @tab @t{system}
  261. @item @t{fcntl} @tab @t{recv} @tab @t{tcdrain}
  262. @item @t{fsync} @tab @t{recvfrom} @tab @t{wait}
  263. @item @t{lseek} @tab @t{recvmsg} @tab @t{waitpid}
  264. @item @t{msync} @tab @t{send} @tab @t{write}
  265. @item @t{nanosleep}
  266. @end multitable
  267. @noindent
  268. All library functions that call these functions (such as
  269. @code{printf}) are also cancellation points.
  270. @comment pthread.h
  271. @comment POSIX
  272. @deftypefun int pthread_setcancelstate (int @var{state}, int *@var{oldstate})
  273. @code{pthread_setcancelstate} changes the cancellation state for the
  274. calling thread -- that is, whether cancellation requests are ignored or
  275. not. The @var{state} argument is the new cancellation state: either
  276. @code{PTHREAD_CANCEL_ENABLE} to enable cancellation, or
  277. @code{PTHREAD_CANCEL_DISABLE} to disable cancellation (cancellation
  278. requests are ignored).
  279. If @var{oldstate} is not @code{NULL}, the previous cancellation state is
  280. stored in the location pointed to by @var{oldstate}, and can thus be
  281. restored later by another call to @code{pthread_setcancelstate}.
  282. If the @var{state} argument is not @code{PTHREAD_CANCEL_ENABLE} or
  283. @code{PTHREAD_CANCEL_DISABLE}, @code{pthread_setcancelstate} fails and
  284. returns @code{EINVAL}. Otherwise it returns 0.
  285. @end deftypefun
  286. @comment pthread.h
  287. @comment POSIX
  288. @deftypefun int pthread_setcanceltype (int @var{type}, int *@var{oldtype})
  289. @code{pthread_setcanceltype} changes the type of responses to
  290. cancellation requests for the calling thread: asynchronous (immediate)
  291. or deferred. The @var{type} argument is the new cancellation type:
  292. either @code{PTHREAD_CANCEL_ASYNCHRONOUS} to cancel the calling thread
  293. as soon as the cancellation request is received, or
  294. @code{PTHREAD_CANCEL_DEFERRED} to keep the cancellation request pending
  295. until the next cancellation point. If @var{oldtype} is not @code{NULL},
  296. the previous cancellation state is stored in the location pointed to by
  297. @var{oldtype}, and can thus be restored later by another call to
  298. @code{pthread_setcanceltype}.
  299. If the @var{type} argument is not @code{PTHREAD_CANCEL_DEFERRED} or
  300. @code{PTHREAD_CANCEL_ASYNCHRONOUS}, @code{pthread_setcanceltype} fails
  301. and returns @code{EINVAL}. Otherwise it returns 0.
  302. @end deftypefun
  303. @comment pthread.h
  304. @comment POSIX
  305. @deftypefun void pthread_testcancel (@var{void})
  306. @code{pthread_testcancel} does nothing except testing for pending
  307. cancellation and executing it. Its purpose is to introduce explicit
  308. checks for cancellation in long sequences of code that do not call
  309. cancellation point functions otherwise.
  310. @end deftypefun
  311. @node Cleanup Handlers
  312. @section Cleanup Handlers
  313. Cleanup handlers are functions that get called when a thread terminates,
  314. either by calling @code{pthread_exit} or because of
  315. cancellation. Cleanup handlers are installed and removed following a
  316. stack-like discipline.
  317. The purpose of cleanup handlers is to free the resources that a thread
  318. may hold at the time it terminates. In particular, if a thread exits or
  319. is cancelled while it owns a locked mutex, the mutex will remain locked
  320. forever and prevent other threads from executing normally. The best way
  321. to avoid this is, just before locking the mutex, to install a cleanup
  322. handler whose effect is to unlock the mutex. Cleanup handlers can be
  323. used similarly to free blocks allocated with @code{malloc} or close file
  324. descriptors on thread termination.
  325. Here is how to lock a mutex @var{mut} in such a way that it will be
  326. unlocked if the thread is canceled while @var{mut} is locked:
  327. @smallexample
  328. pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
  329. pthread_mutex_lock(&mut);
  330. /* do some work */
  331. pthread_mutex_unlock(&mut);
  332. pthread_cleanup_pop(0);
  333. @end smallexample
  334. Equivalently, the last two lines can be replaced by
  335. @smallexample
  336. pthread_cleanup_pop(1);
  337. @end smallexample
  338. Notice that the code above is safe only in deferred cancellation mode
  339. (see @code{pthread_setcanceltype}). In asynchronous cancellation mode, a
  340. cancellation can occur between @code{pthread_cleanup_push} and
  341. @code{pthread_mutex_lock}, or between @code{pthread_mutex_unlock} and
  342. @code{pthread_cleanup_pop}, resulting in both cases in the thread trying
  343. to unlock a mutex not locked by the current thread. This is the main
  344. reason why asynchronous cancellation is difficult to use.
  345. If the code above must also work in asynchronous cancellation mode,
  346. then it must switch to deferred mode for locking and unlocking the
  347. mutex:
  348. @smallexample
  349. pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
  350. pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
  351. pthread_mutex_lock(&mut);
  352. /* do some work */
  353. pthread_cleanup_pop(1);
  354. pthread_setcanceltype(oldtype, NULL);
  355. @end smallexample
  356. The code above can be rewritten in a more compact and efficient way,
  357. using the non-portable functions @code{pthread_cleanup_push_defer_np}
  358. and @code{pthread_cleanup_pop_restore_np}:
  359. @smallexample
  360. pthread_cleanup_push_defer_np(pthread_mutex_unlock, (void *) &mut);
  361. pthread_mutex_lock(&mut);
  362. /* do some work */
  363. pthread_cleanup_pop_restore_np(1);
  364. @end smallexample
  365. @comment pthread.h
  366. @comment POSIX
  367. @deftypefun void pthread_cleanup_push (void (*@var{routine}) (void *), void *@var{arg})
  368. @code{pthread_cleanup_push} installs the @var{routine} function with
  369. argument @var{arg} as a cleanup handler. From this point on to the
  370. matching @code{pthread_cleanup_pop}, the function @var{routine} will be
  371. called with arguments @var{arg} when the thread terminates, either
  372. through @code{pthread_exit} or by cancellation. If several cleanup
  373. handlers are active at that point, they are called in LIFO order: the
  374. most recently installed handler is called first.
  375. @end deftypefun
  376. @comment pthread.h
  377. @comment POSIX
  378. @deftypefun void pthread_cleanup_pop (int @var{execute})
  379. @code{pthread_cleanup_pop} removes the most recently installed cleanup
  380. handler. If the @var{execute} argument is not 0, it also executes the
  381. handler, by calling the @var{routine} function with arguments
  382. @var{arg}. If the @var{execute} argument is 0, the handler is only
  383. removed but not executed.
  384. @end deftypefun
  385. Matching pairs of @code{pthread_cleanup_push} and
  386. @code{pthread_cleanup_pop} must occur in the same function, at the same
  387. level of block nesting. Actually, @code{pthread_cleanup_push} and
  388. @code{pthread_cleanup_pop} are macros, and the expansion of
  389. @code{pthread_cleanup_push} introduces an open brace @code{@{} with the
  390. matching closing brace @code{@}} being introduced by the expansion of the
  391. matching @code{pthread_cleanup_pop}.
  392. @comment pthread.h
  393. @comment GNU
  394. @deftypefun void pthread_cleanup_push_defer_np (void (*@var{routine}) (void *), void *@var{arg})
  395. @code{pthread_cleanup_push_defer_np} is a non-portable extension that
  396. combines @code{pthread_cleanup_push} and @code{pthread_setcanceltype}.
  397. It pushes a cleanup handler just as @code{pthread_cleanup_push} does,
  398. but also saves the current cancellation type and sets it to deferred
  399. cancellation. This ensures that the cleanup mechanism is effective even
  400. if the thread was initially in asynchronous cancellation mode.
  401. @end deftypefun
  402. @comment pthread.h
  403. @comment GNU
  404. @deftypefun void pthread_cleanup_pop_restore_np (int @var{execute})
  405. @code{pthread_cleanup_pop_restore_np} pops a cleanup handler introduced
  406. by @code{pthread_cleanup_push_defer_np}, and restores the cancellation
  407. type to its value at the time @code{pthread_cleanup_push_defer_np} was
  408. called.
  409. @end deftypefun
  410. @code{pthread_cleanup_push_defer_np} and
  411. @code{pthread_cleanup_pop_restore_np} must occur in matching pairs, at
  412. the same level of block nesting.
  413. The sequence
  414. @smallexample
  415. pthread_cleanup_push_defer_np(routine, arg);
  416. ...
  417. pthread_cleanup_pop_defer_np(execute);
  418. @end smallexample
  419. @noindent
  420. is functionally equivalent to (but more compact and efficient than)
  421. @smallexample
  422. @{
  423. int oldtype;
  424. pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
  425. pthread_cleanup_push(routine, arg);
  426. ...
  427. pthread_cleanup_pop(execute);
  428. pthread_setcanceltype(oldtype, NULL);
  429. @}
  430. @end smallexample
  431. @node Mutexes
  432. @section Mutexes
  433. A mutex is a MUTual EXclusion device, and is useful for protecting
  434. shared data structures from concurrent modifications, and implementing
  435. critical sections and monitors.
  436. A mutex has two possible states: unlocked (not owned by any thread),
  437. and locked (owned by one thread). A mutex can never be owned by two
  438. different threads simultaneously. A thread attempting to lock a mutex
  439. that is already locked by another thread is suspended until the owning
  440. thread unlocks the mutex first.
  441. None of the mutex functions is a cancellation point, not even
  442. @code{pthread_mutex_lock}, in spite of the fact that it can suspend a
  443. thread for arbitrary durations. This way, the status of mutexes at
  444. cancellation points is predictable, allowing cancellation handlers to
  445. unlock precisely those mutexes that need to be unlocked before the
  446. thread stops executing. Consequently, threads using deferred
  447. cancellation should never hold a mutex for extended periods of time.
  448. It is not safe to call mutex functions from a signal handler. In
  449. particular, calling @code{pthread_mutex_lock} or
  450. @code{pthread_mutex_unlock} from a signal handler may deadlock the
  451. calling thread.
  452. @comment pthread.h
  453. @comment POSIX
  454. @deftypefun int pthread_mutex_init (pthread_mutex_t *@var{mutex}, const pthread_mutexattr_t *@var{mutexattr})
  455. @code{pthread_mutex_init} initializes the mutex object pointed to by
  456. @var{mutex} according to the mutex attributes specified in @var{mutexattr}.
  457. If @var{mutexattr} is @code{NULL}, default attributes are used instead.
  458. The LinuxThreads implementation supports only one mutex attribute,
  459. the @var{mutex kind}, which is either ``fast'', ``recursive'', or
  460. ``error checking''. The kind of a mutex determines whether
  461. it can be locked again by a thread that already owns it.
  462. The default kind is ``fast''.
  463. Variables of type @code{pthread_mutex_t} can also be initialized
  464. statically, using the constants @code{PTHREAD_MUTEX_INITIALIZER} (for
  465. fast mutexes), @code{PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP} (for
  466. recursive mutexes), and @code{PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP}
  467. (for error checking mutexes).
  468. @code{pthread_mutex_init} always returns 0.
  469. @end deftypefun
  470. @comment pthread.h
  471. @comment POSIX
  472. @deftypefun int pthread_mutex_lock (pthread_mutex_t *mutex))
  473. @code{pthread_mutex_lock} locks the given mutex. If the mutex is
  474. currently unlocked, it becomes locked and owned by the calling thread,
  475. and @code{pthread_mutex_lock} returns immediately. If the mutex is
  476. already locked by another thread, @code{pthread_mutex_lock} suspends the
  477. calling thread until the mutex is unlocked.
  478. If the mutex is already locked by the calling thread, the behavior of
  479. @code{pthread_mutex_lock} depends on the kind of the mutex. If the mutex
  480. is of the ``fast'' kind, the calling thread is suspended. It will
  481. remain suspended forever, because no other thread can unlock the mutex.
  482. If the mutex is of the ``error checking'' kind, @code{pthread_mutex_lock}
  483. returns immediately with the error code @code{EDEADLK}. If the mutex is
  484. of the ``recursive'' kind, @code{pthread_mutex_lock} succeeds and
  485. returns immediately, recording the number of times the calling thread
  486. has locked the mutex. An equal number of @code{pthread_mutex_unlock}
  487. operations must be performed before the mutex returns to the unlocked
  488. state.
  489. @end deftypefun
  490. @comment pthread.h
  491. @comment POSIX
  492. @deftypefun int pthread_mutex_trylock (pthread_mutex_t *@var{mutex})
  493. @code{pthread_mutex_trylock} behaves identically to
  494. @code{pthread_mutex_lock}, except that it does not block the calling
  495. thread if the mutex is already locked by another thread (or by the
  496. calling thread in the case of a ``fast'' mutex). Instead,
  497. @code{pthread_mutex_trylock} returns immediately with the error code
  498. @code{EBUSY}.
  499. @end deftypefun
  500. @comment pthread.h
  501. @comment POSIX
  502. @deftypefun int pthread_mutex_unlock (pthread_mutex_t *@var{mutex})
  503. @code{pthread_mutex_unlock} unlocks the given mutex. The mutex is
  504. assumed to be locked and owned by the calling thread on entrance to
  505. @code{pthread_mutex_unlock}. If the mutex is of the ``fast'' kind,
  506. @code{pthread_mutex_unlock} always returns it to the unlocked state. If
  507. it is of the ``recursive'' kind, it decrements the locking count of the
  508. mutex (number of @code{pthread_mutex_lock} operations performed on it by
  509. the calling thread), and only when this count reaches zero is the mutex
  510. actually unlocked.
  511. On ``error checking'' mutexes, @code{pthread_mutex_unlock} actually
  512. checks at run-time that the mutex is locked on entrance, and that it was
  513. locked by the same thread that is now calling
  514. @code{pthread_mutex_unlock}. If these conditions are not met,
  515. @code{pthread_mutex_unlock} returns @code{EPERM}, and the mutex remains
  516. unchanged. ``Fast'' and ``recursive'' mutexes perform no such checks,
  517. thus allowing a locked mutex to be unlocked by a thread other than its
  518. owner. This is non-portable behavior and must not be relied upon.
  519. @end deftypefun
  520. @comment pthread.h
  521. @comment POSIX
  522. @deftypefun int pthread_mutex_destroy (pthread_mutex_t *@var{mutex})
  523. @code{pthread_mutex_destroy} destroys a mutex object, freeing the
  524. resources it might hold. The mutex must be unlocked on entrance. In the
  525. LinuxThreads implementation, no resources are associated with mutex
  526. objects, thus @code{pthread_mutex_destroy} actually does nothing except
  527. checking that the mutex is unlocked.
  528. If the mutex is locked by some thread, @code{pthread_mutex_destroy}
  529. returns @code{EBUSY}. Otherwise it returns 0.
  530. @end deftypefun
  531. If any of the above functions (except @code{pthread_mutex_init})
  532. is applied to an uninitialized mutex, they will simply return
  533. @code{EINVAL} and do nothing.
  534. A shared global variable @var{x} can be protected by a mutex as follows:
  535. @smallexample
  536. int x;
  537. pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
  538. @end smallexample
  539. All accesses and modifications to @var{x} should be bracketed by calls to
  540. @code{pthread_mutex_lock} and @code{pthread_mutex_unlock} as follows:
  541. @smallexample
  542. pthread_mutex_lock(&mut);
  543. /* operate on x */
  544. pthread_mutex_unlock(&mut);
  545. @end smallexample
  546. Mutex attributes can be specified at mutex creation time, by passing a
  547. mutex attribute object as second argument to @code{pthread_mutex_init}.
  548. Passing @code{NULL} is equivalent to passing a mutex attribute object
  549. with all attributes set to their default values.
  550. @comment pthread.h
  551. @comment POSIX
  552. @deftypefun int pthread_mutexattr_init (pthread_mutexattr_t *@var{attr})
  553. @code{pthread_mutexattr_init} initializes the mutex attribute object
  554. @var{attr} and fills it with default values for the attributes.
  555. This function always returns 0.
  556. @end deftypefun
  557. @comment pthread.h
  558. @comment POSIX
  559. @deftypefun int pthread_mutexattr_destroy (pthread_mutexattr_t *@var{attr})
  560. @code{pthread_mutexattr_destroy} destroys a mutex attribute object,
  561. which must not be reused until it is
  562. reinitialized. @code{pthread_mutexattr_destroy} does nothing in the
  563. LinuxThreads implementation.
  564. This function always returns 0.
  565. @end deftypefun
  566. LinuxThreads supports only one mutex attribute: the mutex kind, which is
  567. either @code{PTHREAD_MUTEX_FAST_NP} for ``fast'' mutexes,
  568. @code{PTHREAD_MUTEX_RECURSIVE_NP} for ``recursive'' mutexes, or
  569. @code{PTHREAD_MUTEX_ERRORCHECK_NP} for ``error checking'' mutexes. As
  570. the @code{NP} suffix indicates, this is a non-portable extension to the
  571. POSIX standard and should not be employed in portable programs.
  572. The mutex kind determines what happens if a thread attempts to lock a
  573. mutex it already owns with @code{pthread_mutex_lock}. If the mutex is of
  574. the ``fast'' kind, @code{pthread_mutex_lock} simply suspends the calling
  575. thread forever. If the mutex is of the ``error checking'' kind,
  576. @code{pthread_mutex_lock} returns immediately with the error code
  577. @code{EDEADLK}. If the mutex is of the ``recursive'' kind, the call to
  578. @code{pthread_mutex_lock} returns immediately with a success return
  579. code. The number of times the thread owning the mutex has locked it is
  580. recorded in the mutex. The owning thread must call
  581. @code{pthread_mutex_unlock} the same number of times before the mutex
  582. returns to the unlocked state.
  583. The default mutex kind is ``fast'', that is, @code{PTHREAD_MUTEX_FAST_NP}.
  584. @comment pthread.h
  585. @comment GNU
  586. @deftypefun int pthread_mutexattr_setkind_np (pthread_mutexattr_t *@var{attr}, int @var{kind})
  587. @code{pthread_mutexattr_setkind_np} sets the mutex kind attribute in
  588. @var{attr} to the value specified by @var{kind}.
  589. If @var{kind} is not @code{PTHREAD_MUTEX_FAST_NP},
  590. @code{PTHREAD_MUTEX_RECURSIVE_NP}, or
  591. @code{PTHREAD_MUTEX_ERRORCHECK_NP}, this function will return
  592. @code{EINVAL} and leave @var{attr} unchanged.
  593. @end deftypefun
  594. @comment pthread.h
  595. @comment GNU
  596. @deftypefun int pthread_mutexattr_getkind_np (const pthread_mutexattr_t *@var{attr}, int *@var{kind})
  597. @code{pthread_mutexattr_getkind_np} retrieves the current value of the
  598. mutex kind attribute in @var{attr} and stores it in the location pointed
  599. to by @var{kind}.
  600. This function always returns 0.
  601. @end deftypefun
  602. @node Condition Variables
  603. @section Condition Variables
  604. A condition (short for ``condition variable'') is a synchronization
  605. device that allows threads to suspend execution until some predicate on
  606. shared data is satisfied. The basic operations on conditions are: signal
  607. the condition (when the predicate becomes true), and wait for the
  608. condition, suspending the thread execution until another thread signals
  609. the condition.
  610. A condition variable must always be associated with a mutex, to avoid
  611. the race condition where a thread prepares to wait on a condition
  612. variable and another thread signals the condition just before the first
  613. thread actually waits on it.
  614. @comment pthread.h
  615. @comment POSIX
  616. @deftypefun int pthread_cond_init (pthread_cond_t *@var{cond}, pthread_condattr_t *cond_@var{attr})
  617. @code{pthread_cond_init} initializes the condition variable @var{cond},
  618. using the condition attributes specified in @var{cond_attr}, or default
  619. attributes if @var{cond_attr} is @code{NULL}. The LinuxThreads
  620. implementation supports no attributes for conditions, hence the
  621. @var{cond_attr} parameter is actually ignored.
  622. Variables of type @code{pthread_cond_t} can also be initialized
  623. statically, using the constant @code{PTHREAD_COND_INITIALIZER}.
  624. This function always returns 0.
  625. @end deftypefun
  626. @comment pthread.h
  627. @comment POSIX
  628. @deftypefun int pthread_cond_signal (pthread_cond_t *@var{cond})
  629. @code{pthread_cond_signal} restarts one of the threads that are waiting
  630. on the condition variable @var{cond}. If no threads are waiting on
  631. @var{cond}, nothing happens. If several threads are waiting on
  632. @var{cond}, exactly one is restarted, but it is not specified which.
  633. This function always returns 0.
  634. @end deftypefun
  635. @comment pthread.h
  636. @comment POSIX
  637. @deftypefun int pthread_cond_broadcast (pthread_cond_t *@var{cond})
  638. @code{pthread_cond_broadcast} restarts all the threads that are waiting
  639. on the condition variable @var{cond}. Nothing happens if no threads are
  640. waiting on @var{cond}.
  641. This function always returns 0.
  642. @end deftypefun
  643. @comment pthread.h
  644. @comment POSIX
  645. @deftypefun int pthread_cond_wait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex})
  646. @code{pthread_cond_wait} atomically unlocks the @var{mutex} (as per
  647. @code{pthread_unlock_mutex}) and waits for the condition variable
  648. @var{cond} to be signaled. The thread execution is suspended and does
  649. not consume any CPU time until the condition variable is signaled. The
  650. @var{mutex} must be locked by the calling thread on entrance to
  651. @code{pthread_cond_wait}. Before returning to the calling thread,
  652. @code{pthread_cond_wait} re-acquires @var{mutex} (as per
  653. @code{pthread_lock_mutex}).
  654. Unlocking the mutex and suspending on the condition variable is done
  655. atomically. Thus, if all threads always acquire the mutex before
  656. signaling the condition, this guarantees that the condition cannot be
  657. signaled (and thus ignored) between the time a thread locks the mutex
  658. and the time it waits on the condition variable.
  659. This function always returns 0.
  660. @end deftypefun
  661. @comment pthread.h
  662. @comment POSIX
  663. @deftypefun int pthread_cond_timedwait (pthread_cond_t *@var{cond}, pthread_mutex_t *@var{mutex}, const struct timespec *@var{abstime})
  664. @code{pthread_cond_timedwait} atomically unlocks @var{mutex} and waits
  665. on @var{cond}, as @code{pthread_cond_wait} does, but it also bounds the
  666. duration of the wait. If @var{cond} has not been signaled before time
  667. @var{abstime}, the mutex @var{mutex} is re-acquired and
  668. @code{pthread_cond_timedwait} returns the error code @code{ETIMEDOUT}.
  669. The wait can also be interrupted by a signal; in that case
  670. @code{pthread_cond_timedwait} returns @code{EINTR}.
  671. The @var{abstime} parameter specifies an absolute time, with the same
  672. origin as @code{time} and @code{gettimeofday}: an @var{abstime} of 0
  673. corresponds to 00:00:00 GMT, January 1, 1970.
  674. @end deftypefun
  675. @comment pthread.h
  676. @comment POSIX
  677. @deftypefun int pthread_cond_destroy (pthread_cond_t *@var{cond})
  678. @code{pthread_cond_destroy} destroys the condition variable @var{cond},
  679. freeing the resources it might hold. If any threads are waiting on the
  680. condition variable, @code{pthread_cond_destroy} leaves @var{cond}
  681. untouched and returns @code{EBUSY}. Otherwise it returns 0, and
  682. @var{cond} must not be used again until it is reinitialized.
  683. In the LinuxThreads implementation, no resources are associated with
  684. condition variables, so @code{pthread_cond_destroy} actually does
  685. nothing.
  686. @end deftypefun
  687. @code{pthread_cond_wait} and @code{pthread_cond_timedwait} are
  688. cancellation points. If a thread is cancelled while suspended in one of
  689. these functions, the thread immediately resumes execution, relocks the
  690. mutex specified by @var{mutex}, and finally executes the cancellation.
  691. Consequently, cleanup handlers are assured that @var{mutex} is locked
  692. when they are called.
  693. It is not safe to call the condition variable functions from a signal
  694. handler. In particular, calling @code{pthread_cond_signal} or
  695. @code{pthread_cond_broadcast} from a signal handler may deadlock the
  696. calling thread.
  697. Consider two shared variables @var{x} and @var{y}, protected by the
  698. mutex @var{mut}, and a condition variable @var{cond} that is to be
  699. signaled whenever @var{x} becomes greater than @var{y}.
  700. @smallexample
  701. int x,y;
  702. pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
  703. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  704. @end smallexample
  705. Waiting until @var{x} is greater than @var{y} is performed as follows:
  706. @smallexample
  707. pthread_mutex_lock(&mut);
  708. while (x <= y) @{
  709. pthread_cond_wait(&cond, &mut);
  710. @}
  711. /* operate on x and y */
  712. pthread_mutex_unlock(&mut);
  713. @end smallexample
  714. Modifications on @var{x} and @var{y} that may cause @var{x} to become greater than
  715. @var{y} should signal the condition if needed:
  716. @smallexample
  717. pthread_mutex_lock(&mut);
  718. /* modify x and y */
  719. if (x > y) pthread_cond_broadcast(&cond);
  720. pthread_mutex_unlock(&mut);
  721. @end smallexample
  722. If it can be proved that at most one waiting thread needs to be waken
  723. up (for instance, if there are only two threads communicating through
  724. @var{x} and @var{y}), @code{pthread_cond_signal} can be used as a slightly more
  725. efficient alternative to @code{pthread_cond_broadcast}. In doubt, use
  726. @code{pthread_cond_broadcast}.
  727. To wait for @var{x} to becomes greater than @var{y} with a timeout of 5
  728. seconds, do:
  729. @smallexample
  730. struct timeval now;
  731. struct timespec timeout;
  732. int retcode;
  733. pthread_mutex_lock(&mut);
  734. gettimeofday(&now);
  735. timeout.tv_sec = now.tv_sec + 5;
  736. timeout.tv_nsec = now.tv_usec * 1000;
  737. retcode = 0;
  738. while (x <= y && retcode != ETIMEDOUT) @{
  739. retcode = pthread_cond_timedwait(&cond, &mut, &timeout);
  740. @}
  741. if (retcode == ETIMEDOUT) @{
  742. /* timeout occurred */
  743. @} else @{
  744. /* operate on x and y */
  745. @}
  746. pthread_mutex_unlock(&mut);
  747. @end smallexample
  748. Condition attributes can be specified at condition creation time, by
  749. passing a condition attribute object as second argument to
  750. @code{pthread_cond_init}. Passing @code{NULL} is equivalent to passing
  751. a condition attribute object with all attributes set to their default
  752. values.
  753. The LinuxThreads implementation supports no attributes for
  754. conditions. The functions on condition attributes are included only for
  755. compliance with the POSIX standard.
  756. @comment pthread.h
  757. @comment POSIX
  758. @deftypefun int pthread_condattr_init (pthread_condattr_t *@var{attr})
  759. @deftypefunx int pthread_condattr_destroy (pthread_condattr_t *@var{attr})
  760. @code{pthread_condattr_init} initializes the condition attribute object
  761. @var{attr} and fills it with default values for the attributes.
  762. @code{pthread_condattr_destroy} destroys the condition attribute object
  763. @var{attr}.
  764. Both functions do nothing in the LinuxThreads implementation.
  765. @code{pthread_condattr_init} and @code{pthread_condattr_destroy} always
  766. return 0.
  767. @end deftypefun
  768. @node POSIX Semaphores
  769. @section POSIX Semaphores
  770. @vindex SEM_VALUE_MAX
  771. Semaphores are counters for resources shared between threads. The
  772. basic operations on semaphores are: increment the counter atomically,
  773. and wait until the counter is non-null and decrement it atomically.
  774. Semaphores have a maximum value past which they cannot be incremented.
  775. The macro @code{SEM_VALUE_MAX} is defined to be this maximum value. In
  776. the GNU C library, @code{SEM_VALUE_MAX} is equal to @code{INT_MAX}
  777. (@pxref{Range of Type}), but it may be much smaller on other systems.
  778. The pthreads library implements POSIX 1003.1b semaphores. These should
  779. not be confused with System V semaphores (@code{ipc}, @code{semctl} and
  780. @code{semop}).
  781. @c !!! SysV IPC is not doc'd at all in our manual
  782. All the semaphore functions and macros are defined in @file{semaphore.h}.
  783. @comment semaphore.h
  784. @comment POSIX
  785. @deftypefun int sem_init (sem_t *@var{sem}, int @var{pshared}, unsigned int @var{value})
  786. @code{sem_init} initializes the semaphore object pointed to by
  787. @var{sem}. The count associated with the semaphore is set initially to
  788. @var{value}. The @var{pshared} argument indicates whether the semaphore
  789. is local to the current process (@var{pshared} is zero) or is to be
  790. shared between several processes (@var{pshared} is not zero).
  791. On success @code{sem_init} returns 0. On failure it returns -1 and sets
  792. @var{errno} to one of the following values:
  793. @table @code
  794. @item EINVAL
  795. @var{value} exceeds the maximal counter value @code{SEM_VALUE_MAX}
  796. @item ENOSYS
  797. @var{pshared} is not zero. LinuxThreads currently does not support
  798. process-shared semaphores. (This will eventually change.)
  799. @end table
  800. @end deftypefun
  801. @comment semaphore.h
  802. @comment POSIX
  803. @deftypefun int sem_destroy (sem_t * @var{sem})
  804. @code{sem_destroy} destroys a semaphore object, freeing the resources it
  805. might hold. If any threads are waiting on the semaphore when
  806. @code{sem_destroy} is called, it fails and sets @var{errno} to
  807. @code{EBUSY}.
  808. In the LinuxThreads implementation, no resources are associated with
  809. semaphore objects, thus @code{sem_destroy} actually does nothing except
  810. checking that no thread is waiting on the semaphore. This will change
  811. when process-shared semaphores are implemented.
  812. @end deftypefun
  813. @comment semaphore.h
  814. @comment POSIX
  815. @deftypefun int sem_wait (sem_t * @var{sem})
  816. @code{sem_wait} suspends the calling thread until the semaphore pointed
  817. to by @var{sem} has non-zero count. It then atomically decreases the
  818. semaphore count.
  819. @code{sem_wait} is a cancellation point. It always returns 0.
  820. @end deftypefun
  821. @comment semaphore.h
  822. @comment POSIX
  823. @deftypefun int sem_trywait (sem_t * @var{sem})
  824. @code{sem_trywait} is a non-blocking variant of @code{sem_wait}. If the
  825. semaphore pointed to by @var{sem} has non-zero count, the count is
  826. atomically decreased and @code{sem_trywait} immediately returns 0. If
  827. the semaphore count is zero, @code{sem_trywait} immediately returns -1
  828. and sets errno to @code{EAGAIN}.
  829. @end deftypefun
  830. @comment semaphore.h
  831. @comment POSIX
  832. @deftypefun int sem_post (sem_t * @var{sem})
  833. @code{sem_post} atomically increases the count of the semaphore pointed to
  834. by @var{sem}. This function never blocks.
  835. @c !!! This para appears not to agree with the code.
  836. On processors supporting atomic compare-and-swap (Intel 486, Pentium and
  837. later, Alpha, PowerPC, MIPS II, Motorola 68k, Ultrasparc), the
  838. @code{sem_post} function is can safely be called from signal handlers.
  839. This is the only thread synchronization function provided by POSIX
  840. threads that is async-signal safe. On the Intel 386 and earlier Sparc
  841. chips, the current LinuxThreads implementation of @code{sem_post} is not
  842. async-signal safe, because the hardware does not support the required
  843. atomic operations.
  844. @code{sem_post} always succeeds and returns 0, unless the semaphore
  845. count would exceed @code{SEM_VALUE_MAX} after being incremented. In
  846. that case @code{sem_post} returns -1 and sets @var{errno} to
  847. @code{EINVAL}. The semaphore count is left unchanged.
  848. @end deftypefun
  849. @comment semaphore.h
  850. @comment POSIX
  851. @deftypefun int sem_getvalue (sem_t * @var{sem}, int * @var{sval})
  852. @code{sem_getvalue} stores in the location pointed to by @var{sval} the
  853. current count of the semaphore @var{sem}. It always returns 0.
  854. @end deftypefun
  855. @node Thread-Specific Data
  856. @section Thread-Specific Data
  857. Programs often need global or static variables that have different
  858. values in different threads. Since threads share one memory space, this
  859. cannot be achieved with regular variables. Thread-specific data is the
  860. POSIX threads answer to this need.
  861. Each thread possesses a private memory block, the thread-specific data
  862. area, or TSD area for short. This area is indexed by TSD keys. The TSD
  863. area associates values of type @code{void *} to TSD keys. TSD keys are
  864. common to all threads, but the value associated with a given TSD key can
  865. be different in each thread.
  866. For concreteness, the TSD areas can be viewed as arrays of @code{void *}
  867. pointers, TSD keys as integer indices into these arrays, and the value
  868. of a TSD key as the value of the corresponding array element in the
  869. calling thread.
  870. When a thread is created, its TSD area initially associates @code{NULL}
  871. with all keys.
  872. @comment pthread.h
  873. @comment POSIX
  874. @deftypefun int pthread_key_create (pthread_key_t *@var{key}, void (*destr_function) (void *))
  875. @code{pthread_key_create} allocates a new TSD key. The key is stored in
  876. the location pointed to by @var{key}. There is a limit of
  877. @code{PTHREAD_KEYS_MAX} on the number of keys allocated at a given
  878. time. The value initially associated with the returned key is
  879. @code{NULL} in all currently executing threads.
  880. The @var{destr_function} argument, if not @code{NULL}, specifies a
  881. destructor function associated with the key. When a thread terminates
  882. via @code{pthread_exit} or by cancellation, @var{destr_function} is
  883. called on the value associated with the key in that thread. The
  884. @var{destr_function} is not called if a key is deleted with
  885. @code{pthread_key_delete} or a value is changed with
  886. @code{pthread_setspecific}. The order in which destructor functions are
  887. called at thread termination time is unspecified.
  888. Before the destructor function is called, the @code{NULL} value is
  889. associated with the key in the current thread. A destructor function
  890. might, however, re-associate non-@code{NULL} values to that key or some
  891. other key. To deal with this, if after all the destructors have been
  892. called for all non-@code{NULL} values, there are still some
  893. non-@code{NULL} values with associated destructors, then the process is
  894. repeated. The LinuxThreads implementation stops the process after
  895. @code{PTHREAD_DESTRUCTOR_ITERATIONS} iterations, even if some
  896. non-@code{NULL} values with associated descriptors remain. Other
  897. implementations may loop indefinitely.
  898. @code{pthread_key_create} returns 0 unless @code{PTHREAD_KEYS_MAX} keys
  899. have already been allocated, in which case it fails and returns
  900. @code{EAGAIN}.
  901. @end deftypefun
  902. @comment pthread.h
  903. @comment POSIX
  904. @deftypefun int pthread_key_delete (pthread_key_t @var{key})
  905. @code{pthread_key_delete} deallocates a TSD key. It does not check
  906. whether non-@code{NULL} values are associated with that key in the
  907. currently executing threads, nor call the destructor function associated
  908. with the key.
  909. If there is no such key @var{key}, it returns @code{EINVAL}. Otherwise
  910. it returns 0.
  911. @end deftypefun
  912. @comment pthread.h
  913. @comment POSIX
  914. @deftypefun int pthread_setspecific (pthread_key_t @var{key}, const void *@var{pointer})
  915. @code{pthread_setspecific} changes the value associated with @var{key}
  916. in the calling thread, storing the given @var{pointer} instead.
  917. If there is no such key @var{key}, it returns @code{EINVAL}. Otherwise
  918. it returns 0.
  919. @end deftypefun
  920. @comment pthread.h
  921. @comment POSIX
  922. @deftypefun {void *} pthread_getspecific (pthread_key_t @var{key})
  923. @code{pthread_getspecific} returns the value currently associated with
  924. @var{key} in the calling thread.
  925. If there is no such key @var{key}, it returns @code{NULL}.
  926. @end deftypefun
  927. The following code fragment allocates a thread-specific array of 100
  928. characters, with automatic reclaimation at thread exit:
  929. @smallexample
  930. /* Key for the thread-specific buffer */
  931. static pthread_key_t buffer_key;
  932. /* Once-only initialisation of the key */
  933. static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
  934. /* Allocate the thread-specific buffer */
  935. void buffer_alloc(void)
  936. @{
  937. pthread_once(&buffer_key_once, buffer_key_alloc);
  938. pthread_setspecific(buffer_key, malloc(100));
  939. @}
  940. /* Return the thread-specific buffer */
  941. char * get_buffer(void)
  942. @{
  943. return (char *) pthread_getspecific(buffer_key);
  944. @}
  945. /* Allocate the key */
  946. static void buffer_key_alloc()
  947. @{
  948. pthread_key_create(&buffer_key, buffer_destroy);
  949. @}
  950. /* Free the thread-specific buffer */
  951. static void buffer_destroy(void * buf)
  952. @{
  953. free(buf);
  954. @}
  955. @end smallexample
  956. @node Threads and Signal Handling
  957. @section Threads and Signal Handling
  958. @comment pthread.h
  959. @comment POSIX
  960. @deftypefun int pthread_sigmask (int @var{how}, const sigset_t *@var{newmask}, sigset_t *@var{oldmask})
  961. @code{pthread_sigmask} changes the signal mask for the calling thread as
  962. described by the @var{how} and @var{newmask} arguments. If @var{oldmask}
  963. is not @code{NULL}, the previous signal mask is stored in the location
  964. pointed to by @var{oldmask}.
  965. The meaning of the @var{how} and @var{newmask} arguments is the same as
  966. for @code{sigprocmask}. If @var{how} is @code{SIG_SETMASK}, the signal
  967. mask is set to @var{newmask}. If @var{how} is @code{SIG_BLOCK}, the
  968. signals specified to @var{newmask} are added to the current signal mask.
  969. If @var{how} is @code{SIG_UNBLOCK}, the signals specified to
  970. @var{newmask} are removed from the current signal mask.
  971. Recall that signal masks are set on a per-thread basis, but signal
  972. actions and signal handlers, as set with @code{sigaction}, are shared
  973. between all threads.
  974. The @code{pthread_sigmask} function returns 0 on success, and one of the
  975. following error codes on error:
  976. @table @code
  977. @item EINVAL
  978. @var{how} is not one of @code{SIG_SETMASK}, @code{SIG_BLOCK}, or @code{SIG_UNBLOCK}
  979. @item EFAULT
  980. @var{newmask} or @var{oldmask} point to invalid addresses
  981. @end table
  982. @end deftypefun
  983. @comment pthread.h
  984. @comment POSIX
  985. @deftypefun int pthread_kill (pthread_t @var{thread}, int @var{signo})
  986. @code{pthread_kill} sends signal number @var{signo} to the thread
  987. @var{thread}. The signal is delivered and handled as described in
  988. @ref{Signal Handling}.
  989. @code{pthread_kill} returns 0 on success, one of the following error codes
  990. on error:
  991. @table @code
  992. @item EINVAL
  993. @var{signo} is not a valid signal number
  994. @item ESRCH
  995. The thread @var{thread} does not exist (e.g. it has already terminated)
  996. @end table
  997. @end deftypefun
  998. @comment pthread.h
  999. @comment POSIX
  1000. @deftypefun int sigwait (const sigset_t *@var{set}, int *@var{sig})
  1001. @code{sigwait} suspends the calling thread until one of the signals in
  1002. @var{set} is delivered to the calling thread. It then stores the number
  1003. of the signal received in the location pointed to by @var{sig} and
  1004. returns. The signals in @var{set} must be blocked and not ignored on
  1005. entrance to @code{sigwait}. If the delivered signal has a signal handler
  1006. function attached, that function is @emph{not} called.
  1007. @code{sigwait} is a cancellation point. It always returns 0.
  1008. @end deftypefun
  1009. For @code{sigwait} to work reliably, the signals being waited for must be
  1010. blocked in all threads, not only in the calling thread, since
  1011. otherwise the POSIX semantics for signal delivery do not guarantee
  1012. that it's the thread doing the @code{sigwait} that will receive the signal.
  1013. The best way to achieve this is block those signals before any threads
  1014. are created, and never unblock them in the program other than by
  1015. calling @code{sigwait}.
  1016. Signal handling in LinuxThreads departs significantly from the POSIX
  1017. standard. According to the standard, ``asynchronous'' (external) signals
  1018. are addressed to the whole process (the collection of all threads),
  1019. which then delivers them to one particular thread. The thread that
  1020. actually receives the signal is any thread that does not currently block
  1021. the signal.
  1022. In LinuxThreads, each thread is actually a kernel process with its own
  1023. PID, so external signals are always directed to one particular thread.
  1024. If, for instance, another thread is blocked in @code{sigwait} on that
  1025. signal, it will not be restarted.
  1026. The LinuxThreads implementation of @code{sigwait} installs dummy signal
  1027. handlers for the signals in @var{set} for the duration of the
  1028. wait. Since signal handlers are shared between all threads, other
  1029. threads must not attach their own signal handlers to these signals, or
  1030. alternatively they should all block these signals (which is recommended
  1031. anyway).
  1032. @node Miscellaneous Thread Functions
  1033. @section Miscellaneous Thread Functions
  1034. @comment pthread.h
  1035. @comment POSIX
  1036. @deftypefun {pthread_t} pthread_self (@var{void})
  1037. @code{pthread_self} returns the thread identifier for the calling thread.
  1038. @end deftypefun
  1039. @comment pthread.h
  1040. @comment POSIX
  1041. @deftypefun int pthread_equal (pthread_t thread1, pthread_t thread2)
  1042. @code{pthread_equal} determines if two thread identifiers refer to the same
  1043. thread.
  1044. A non-zero value is returned if @var{thread1} and @var{thread2} refer to
  1045. the same thread. Otherwise, 0 is returned.
  1046. @end deftypefun
  1047. @comment pthread.h
  1048. @comment POSIX
  1049. @deftypefun int pthread_detach (pthread_t @var{th})
  1050. @code{pthread_detach} puts the thread @var{th} in the detached
  1051. state. This guarantees that the memory resources consumed by @var{th}
  1052. will be freed immediately when @var{th} terminates. However, this
  1053. prevents other threads from synchronizing on the termination of @var{th}
  1054. using @code{pthread_join}.
  1055. A thread can be created initially in the detached state, using the
  1056. @code{detachstate} attribute to @code{pthread_create}. In contrast,
  1057. @code{pthread_detach} applies to threads created in the joinable state,
  1058. and which need to be put in the detached state later.
  1059. After @code{pthread_detach} completes, subsequent attempts to perform
  1060. @code{pthread_join} on @var{th} will fail. If another thread is already
  1061. joining the thread @var{th} at the time @code{pthread_detach} is called,
  1062. @code{pthread_detach} does nothing and leaves @var{th} in the joinable
  1063. state.
  1064. On success, 0 is returned. On error, one of the following codes is
  1065. returned:
  1066. @table @code
  1067. @item ESRCH
  1068. No thread could be found corresponding to that specified by @var{th}
  1069. @item EINVAL
  1070. The thread @var{th} is already in the detached state
  1071. @end table
  1072. @end deftypefun
  1073. @comment pthread.h
  1074. @comment POSIX
  1075. @deftypefun int pthread_atfork (void (*@var{prepare})(void), void (*@var{parent})(void), void (*@var{child})(void))
  1076. @code{pthread_atfork} registers handler functions to be called just
  1077. before and just after a new process is created with @code{fork}. The
  1078. @var{prepare} handler will be called from the parent process, just
  1079. before the new process is created. The @var{parent} handler will be
  1080. called from the parent process, just before @code{fork} returns. The
  1081. @var{child} handler will be called from the child process, just before
  1082. @code{fork} returns.
  1083. @code{pthread_atfork} returns 0 on success and a non-zero error code on
  1084. error.
  1085. One or more of the three handlers @var{prepare}, @var{parent} and
  1086. @var{child} can be given as @code{NULL}, meaning that no handler needs
  1087. to be called at the corresponding point.
  1088. @code{pthread_atfork} can be called several times to install several
  1089. sets of handlers. At @code{fork} time, the @var{prepare} handlers are
  1090. called in LIFO order (last added with @code{pthread_atfork}, first
  1091. called before @code{fork}), while the @var{parent} and @var{child}
  1092. handlers are called in FIFO order (first added, first called).
  1093. If there is insufficient memory available to register the handlers,
  1094. @code{pthread_atfork} fails and returns @code{ENOMEM}. Otherwise it
  1095. returns 0.
  1096. @end deftypefun
  1097. To understand the purpose of @code{pthread_atfork}, recall that
  1098. @code{fork} duplicates the whole memory space, including mutexes in
  1099. their current locking state, but only the calling thread: other threads
  1100. are not running in the child process. Thus, if a mutex is locked by a
  1101. thread other than the thread calling @code{fork}, that mutex will remain
  1102. locked forever in the child process, possibly blocking the execution of
  1103. the child process. To avoid this, install handlers with
  1104. @code{pthread_atfork} as follows: the @var{prepare} handler locks the
  1105. global mutexes (in locking order), and the @var{parent} and @var{child}
  1106. handlers unlock them (in reverse order). Alternatively, @var{prepare}
  1107. and @var{parent} can be set to @code{NULL} and @var{child} to a function
  1108. that calls @code{pthread_mutex_init} on the global mutexes.
  1109. @comment pthread.h
  1110. @comment GNU
  1111. @deftypefun void pthread_kill_other_threads_np (@var{void})
  1112. @code{pthread_kill_other_threads_np} is a non-portable LinuxThreads extension.
  1113. It causes all threads in the program to terminate immediately, except
  1114. the calling thread which proceeds normally. It is intended to be
  1115. called just before a thread calls one of the @code{exec} functions,
  1116. e.g. @code{execve}.
  1117. Termination of the other threads is not performed through
  1118. @code{pthread_cancel} and completely bypasses the cancellation
  1119. mechanism. Hence, the current settings for cancellation state and
  1120. cancellation type are ignored, and the cleanup handlers are not
  1121. executed in the terminated threads.
  1122. According to POSIX 1003.1c, a successful @code{exec*} in one of the
  1123. threads should automatically terminate all other threads in the program.
  1124. This behavior is not yet implemented in LinuxThreads. Calling
  1125. @code{pthread_kill_other_threads_np} before @code{exec*} achieves much
  1126. of the same behavior, except that if @code{exec*} ultimately fails, then
  1127. all other threads are already killed.
  1128. @end deftypefun
  1129. @comment pthread.h
  1130. @comment POSIX
  1131. @deftypefun int pthread_once (pthread_once_t *once_@var{control}, void (*@var{init_routine}) (void))
  1132. The purpose of @code{pthread_once} is to ensure that a piece of
  1133. initialization code is executed at most once. The @var{once_control}
  1134. argument points to a static or extern variable statically initialized
  1135. to @code{PTHREAD_ONCE_INIT}.
  1136. The first time @code{pthread_once} is called with a given
  1137. @var{once_control} argument, it calls @var{init_routine} with no
  1138. argument and changes the value of the @var{once_control} variable to
  1139. record that initialization has been performed. Subsequent calls to
  1140. @code{pthread_once} with the same @code{once_control} argument do
  1141. nothing.
  1142. @code{pthread_once} always returns 0.
  1143. @end deftypefun
  1144. @comment pthread.h
  1145. @comment POSIX
  1146. @deftypefun int pthread_setschedparam (pthread_t target_@var{thread}, int @var{policy}, const struct sched_param *@var{param})
  1147. @code{pthread_setschedparam} sets the scheduling parameters for the
  1148. thread @var{target_thread} as indicated by @var{policy} and
  1149. @var{param}. @var{policy} can be either @code{SCHED_OTHER} (regular,
  1150. non-realtime scheduling), @code{SCHED_RR} (realtime, round-robin) or
  1151. @code{SCHED_FIFO} (realtime, first-in first-out). @var{param} specifies
  1152. the scheduling priority for the two realtime policies. See
  1153. @code{sched_setpolicy} for more information on scheduling policies.
  1154. The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}
  1155. are available only to processes with superuser privileges.
  1156. On success, @code{pthread_setschedparam} returns 0. On error it returns
  1157. one of the following codes:
  1158. @table @code
  1159. @item EINVAL
  1160. @var{policy} is not one of @code{SCHED_OTHER}, @code{SCHED_RR},
  1161. @code{SCHED_FIFO}, or the priority value specified by @var{param} is not
  1162. valid for the specified policy
  1163. @item EPERM
  1164. Realtime scheduling was requested but the calling process does not have
  1165. sufficient privileges.
  1166. @item ESRCH
  1167. The @var{target_thread} is invalid or has already terminated
  1168. @item EFAULT
  1169. @var{param} points outside the process memory space
  1170. @end table
  1171. @end deftypefun
  1172. @comment pthread.h
  1173. @comment POSIX
  1174. @deftypefun int pthread_getschedparam (pthread_t target_@var{thread}, int *@var{policy}, struct sched_param *@var{param})
  1175. @code{pthread_getschedparam} retrieves the scheduling policy and
  1176. scheduling parameters for the thread @var{target_thread} and stores them
  1177. in the locations pointed to by @var{policy} and @var{param},
  1178. respectively.
  1179. @code{pthread_getschedparam} returns 0 on success, or one of the
  1180. following error codes on failure:
  1181. @table @code
  1182. @item ESRCH
  1183. The @var{target_thread} is invalid or has already terminated.
  1184. @item EFAULT
  1185. @var{policy} or @var{param} point outside the process memory space.
  1186. @end table
  1187. @end deftypefun