📄 linuxthreads.texi
字号:
@node POSIX Threads@c @node POSIX Threads, , Top, Top@chapter POSIX Threads@c %MENU% The standard threads library@c This chapter needs more work bigtime. -zwThis chapter describes the pthreads (POSIX threads) library. Thislibrary provides support functions for multithreaded programs: threadprimitives, synchronization objects, and so forth. It also implementsPOSIX 1003.1b semaphores (not to be confused with System V semaphores).The threads operations (@samp{pthread_*}) do not use @var{errno}.Instead they return an error code directly. The semaphore operations douse @var{errno}.@menu* Basic Thread Operations:: Creating, terminating, and waiting for threads.* Thread Attributes:: Tuning thread scheduling.* Cancellation:: Stopping a thread before it's done.* Cleanup Handlers:: Deallocating resources when a thread is cancelled.* Mutexes:: One way to synchronize threads.* Condition Variables:: Another way.* POSIX Semaphores:: And a third way.* Thread-Specific Data:: Variables with different values in different threads.* Threads and Signal Handling:: Why you should avoid mixing the two, and how to do it if you must.* Miscellaneous Thread Functions:: A grab bag of utility routines.@end menu@node Basic Thread Operations@section Basic Thread OperationsThese functions are the thread equivalents of @code{fork}, @code{exit},and @code{wait}.@comment pthread.h@comment POSIX@deftypefun int pthread_create (pthread_t * @var{thread}, pthread_attr_t * @var{attr}, void * (*@var{start_routine})(void *), void * @var{arg})@code{pthread_create} creates a new thread of control that executesconcurrently with the calling thread. The new thread calls thefunction @var{start_routine}, passing it @var{arg} as first argument. Thenew thread terminates either explicitly, by calling @code{pthread_exit},or implicitly, by returning from the @var{start_routine} function. Thelatter case is equivalent to calling @code{pthread_exit} with the resultreturned by @var{start_routine} as exit code.The @var{attr} argument specifies thread attributes to be applied to thenew thread. @xref{Thread Attributes}, for details. The @var{attr}argument can also be @code{NULL}, in which case default attributes areused: the created thread is joinable (not detached) and has an ordinary(not realtime) scheduling policy.On success, the identifier of the newly created thread is stored in thelocation pointed by the @var{thread} argument, and a 0 is returned. Onerror, a non-zero error code is returned.This function may return the following errors:@table @code@item EAGAINNot enough system resources to create a process for the new thread,or more than @code{PTHREAD_THREADS_MAX} threads are already active.@end table@end deftypefun@comment pthread.h@comment POSIX@deftypefun void pthread_exit (void *@var{retval})@code{pthread_exit} terminates the execution of the calling thread. Allcleanup handlers (@pxref{Cleanup Handlers}) that have been set for thecalling thread with @code{pthread_cleanup_push} are executed in reverseorder (the most recently pushed handler is executed first). Finalizationfunctions for thread-specific data are then called for all keys thathave non-@code{NULL} values associated with them in the calling thread(@pxref{Thread-Specific Data}). Finally, execution of the callingthread is stopped.The @var{retval} argument is the return value of the thread. It can beretrieved from another thread using @code{pthread_join}.The @code{pthread_exit} function never returns.@end deftypefun@comment pthread.h@comment POSIX@deftypefun int pthread_cancel (pthread_t @var{thread})@code{pthread_cancel} sends a cancellation request to the thread denotedby the @var{thread} argument. If there is no such thread,@code{pthread_cancel} fails and returns @code{ESRCH}. Otherwise itreturns 0. @xref{Cancellation}, for details.@end deftypefun@comment pthread.h@comment POSIX@deftypefun int pthread_join (pthread_t @var{th}, void **thread_@var{return})@code{pthread_join} suspends the execution of the calling thread untilthe thread identified by @var{th} terminates, either by calling@code{pthread_exit} or by being cancelled.If @var{thread_return} is not @code{NULL}, the return value of @var{th}is stored in the location pointed to by @var{thread_return}. The returnvalue of @var{th} is either the argument it gave to @code{pthread_exit},or @code{PTHREAD_CANCELED} if @var{th} was cancelled.The joined thread @code{th} must be in the joinable state: it must nothave been detached using @code{pthread_detach} or the@code{PTHREAD_CREATE_DETACHED} attribute to @code{pthread_create}.When a joinable thread terminates, its memory resources (threaddescriptor and stack) are not deallocated until another thread performs@code{pthread_join} on it. Therefore, @code{pthread_join} must be calledonce for each joinable thread created to avoid memory leaks.At most one thread can wait for the termination of a giventhread. Calling @code{pthread_join} on a thread @var{th} on whichanother thread is already waiting for termination returns an error.@code{pthread_join} is a cancellation point. If a thread is canceledwhile suspended in @code{pthread_join}, the thread execution resumesimmediately and the cancellation is executed without waiting for the@var{th} thread to terminate. If cancellation occurs during@code{pthread_join}, the @var{th} thread remains not joined.On success, the return value of @var{th} is stored in the locationpointed to by @var{thread_return}, and 0 is returned. On error, one ofthe following values is returned:@table @code@item ESRCHNo thread could be found corresponding to that specified by @var{th}.@item EINVALThe @var{th} thread has been detached, or another thread is alreadywaiting on termination of @var{th}.@item EDEADLKThe @var{th} argument refers to the calling thread.@end table@end deftypefun@node Thread Attributes@section Thread Attributes@comment pthread.h@comment POSIXThreads have a number of attributes that may be set at creation time.This is done by filling a thread attribute object @var{attr} of type@code{pthread_attr_t}, then passing it as second argument to@code{pthread_create}. Passing @code{NULL} is equivalent to passing athread attribute object with all attributes set to their default values.Attribute objects are consulted only when creating a new thread. Thesame attribute object can be used for creating several threads.Modifying an attribute object after a call to @code{pthread_create} doesnot change the attributes of the thread previously created.@comment pthread.h@comment POSIX@deftypefun int pthread_attr_init (pthread_attr_t *@var{attr})@code{pthread_attr_init} initializes the thread attribute object@var{attr} and fills it with default values for the attributes. (Thedefault values are listed below for each attribute.)Each attribute @var{attrname} (see below for a list of all attributes)can be individually set using the function@code{pthread_attr_set@var{attrname}} and retrieved using the function@code{pthread_attr_get@var{attrname}}.@end deftypefun@comment pthread.h@comment POSIX@deftypefun int pthread_attr_destroy (pthread_attr_t *@var{attr})@code{pthread_attr_destroy} destroys the attribute object pointed to by@var{attr} releasing any resources associated with it. @var{attr} isleft in an undefined state, and you must not use it again in a call toany pthreads function until it has been reinitialized.@end deftypefun@findex pthread_attr_setinheritsched@findex pthread_attr_setschedparam@findex pthread_attr_setschedpolicy@findex pthread_attr_setscope@comment pthread.h@comment POSIX@deftypefun int pthread_attr_set@var{attr} (pthread_attr_t *@var{obj}, int @var{value})Set attribute @var{attr} to @var{value} in the attribute object pointedto by @var{obj}. See below for a list of possible attributes and thevalues they can take.On success, these functions return 0. If @var{value} is not meaningfulfor the @var{attr} being modified, they will return the error code@code{EINVAL}. Some of the functions have other failure modes; seebelow.@end deftypefun@findex pthread_attr_getinheritsched@findex pthread_attr_getschedparam@findex pthread_attr_getschedpolicy@findex pthread_attr_getscope@comment pthread.h@comment POSIX@deftypefun int pthread_attr_get@var{attr} (const pthread_attr_t *@var{obj}, int *@var{value})Store the current setting of @var{attr} in @var{obj} into the variablepointed to by @var{value}.These functions always return 0.@end deftypefunThe following thread attributes are supported:@table @samp@item detachstateChoose whether the thread is created in the joinable state (value@code{PTHREAD_CREATE_JOINABLE}) or in the detached state(@code{PTHREAD_CREATE_DETACHED}). The default is@code{PTHREAD_CREATE_JOINABLE}.In the joinable state, another thread can synchronize on the threadtermination and recover its termination code using @code{pthread_join},but some of the thread resources are kept allocated after the threadterminates, and reclaimed only when another thread performs@code{pthread_join} on that thread.In the detached state, the thread resources are immediately freed whenit terminates, but @code{pthread_join} cannot be used to synchronize onthe thread termination.A thread created in the joinable state can later be put in the detachedthread using @code{pthread_detach}.@item schedpolicySelect the scheduling policy for the thread: one of @code{SCHED_OTHER}(regular, non-realtime scheduling), @code{SCHED_RR} (realtime,round-robin) or @code{SCHED_FIFO} (realtime, first-in first-out).The default is @code{SCHED_OTHER}.@c Not doc'd in our manual: FIXME.@c See @code{sched_setpolicy} for more information on scheduling policies.The realtime scheduling policies @code{SCHED_RR} and @code{SCHED_FIFO}are available only to processes with superuser privileges.@code{pthread_attr_setschedparam} will fail and return @code{ENOTSUP} ifyou try to set a realtime policy when you are unprivileged.The scheduling policy of a thread can be changed after creation with@code{pthread_setschedparam}.@item schedparamChange the scheduling parameter (the scheduling priority)for the thread. The default is 0.This attribute is not significant if the scheduling policy is@code{SCHED_OTHER}; it only matters for the realtime policies@code{SCHED_RR} and @code{SCHED_FIFO}.The scheduling priority of a thread can be changed after creation with@code{pthread_setschedparam}.@item inheritschedChoose whether the scheduling policy and scheduling parameter for thenewly created thread are determined by the values of the@var{schedpolicy} and @var{schedparam} attributes (value@code{PTHREAD_EXPLICIT_SCHED}) or are inherited from the parent thread(value @code{PTHREAD_INHERIT_SCHED}). The default is@code{PTHREAD_EXPLICIT_SCHED}.@item scopeChoose the scheduling contention scope for the created thread. Thedefault is @code{PTHREAD_SCOPE_SYSTEM}, meaning that the threads contendfor CPU time with all processes running on the machine. In particular,thread priorities are interpreted relative to the priorities of allother processes on the machine. The other possibility,@code{PTHREAD_SCOPE_PROCESS}, means that scheduling contention occursonly between the threads of the running process: thread priorities areinterpreted relative to the priorities of the other threads of theprocess, regardless of the priorities of other processes.@code{PTHREAD_SCOPE_PROCESS} is not supported in LinuxThreads. If youtry to set the scope to this value @code{pthread_attr_setscope} willfail and return @code{ENOTSUP}.@end table@node Cancellation@section CancellationCancellation is the mechanism by which a thread can terminate theexecution of another thread. More precisely, a thread can send acancellation request to another thread. Depending on its settings, thetarget thread can then either ignore the request, honor it immediately,or defer it till it reaches a cancellation point. When threads arefirst created by @code{pthread_create}, they always defer cancellationrequests.When a thread eventually honors a cancellation request, it behaves as if@code{pthread_exit(PTHREAD_CANCELED)} was called. All cleanup handlersare executed in reverse order, finalization functions forthread-specific data are called, and finally the thread stops executing.If the cancelled thread was joinable, the return value@code{PTHREAD_CANCELED} is provided to whichever thread calls@var{pthread_join} on it. See @code{pthread_exit} for more information.Cancellation points are the points where the thread checks for pendingcancellation requests and performs them. The POSIX threads functions@code{pthread_join}, @code{pthread_cond_wait},@code{pthread_cond_timedwait}, @code{pthread_testcancel},@code{sem_wait}, and @code{sigwait} are cancellation points. Inaddition, these system calls are cancellation points:@multitable @columnfractions .33 .33 .33@item @t{accept} @tab @t{open} @tab @t{sendmsg}@item @t{close} @tab @t{pause} @tab @t{sendto}@item @t{connect} @tab @t{read} @tab @t{system}@item @t{fcntl} @tab @t{recv} @tab @t{tcdrain}@item @t{fsync} @tab @t{recvfrom} @tab @t{wait}@item @t{lseek} @tab @t{recvmsg} @tab @t{waitpid}@item @t{msync} @tab @t{send} @tab @t{write}@item @t{nanosleep}@end multitable@noindentAll library functions that call these functions (such as@code{printf}) are also cancellation points.@comment pthread.h@comment POSIX@deftypefun int pthread_setcancelstate (int @var{state}, int *@var{oldstate})@code{pthread_setcancelstate} changes the cancellation state for thecalling thread -- that is, whether cancellation requests are ignored ornot. The @var{state} argument is the new cancellation state: either@code{PTHREAD_CANCEL_ENABLE} to enable cancellation, or@code{PTHREAD_CANCEL_DISABLE} to disable cancellation (cancellationrequests are ignored).If @var{oldstate} is not @code{NULL}, the previous cancellation state isstored in the location pointed to by @var{oldstate}, and can thus berestored later by another call to @code{pthread_setcancelstate}.If the @var{state} argument is not @code{PTHREAD_CANCEL_ENABLE} or@code{PTHREAD_CANCEL_DISABLE}, @code{pthread_setcancelstate} fails andreturns @code{EINVAL}. Otherwise it returns 0.@end deftypefun@comment pthread.h@comment POSIX@deftypefun int pthread_setcanceltype (int @var{type}, int *@var{oldtype})@code{pthread_setcanceltype} changes the type of responses tocancellation requests for the calling thread: asynchronous (immediate)or deferred. The @var{type} argument is the new cancellation type:either @code{PTHREAD_CANCEL_ASYNCHRONOUS} to cancel the calling threadas soon as the cancellation request is received, or@code{PTHREAD_CANCEL_DEFERRED} to keep the cancellation request pendinguntil the next cancellation point. If @var{oldtype} is not @code{NULL},the previous cancellation state is stored in the location pointed to by@var{oldtype}, and can thus be restored later by another call to@code{pthread_setcanceltype}.If the @var{type} argument is not @code{PTHREAD_CANCEL_DEFERRED} or@code{PTHREAD_CANCEL_ASYNCHRONOUS}, @code{pthread_setcanceltype} failsand returns @code{EINVAL}. Otherwise it returns 0.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -