linuxthreads.texi 67 KB

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