9

29
www.lanzarotecaliente.com (press control & click here) 9. POSIX threads mini-reference This chapter is a compact reference to the POSIX.1c standard. 9.1 POSIX 1003.1c-1995 options Pthreads is intended to address a wide variety of audiences. High- performance computational programs can us it to supoort parallel decomposition of loops. Realtime programs can use it to support concurrent realtime I/O. Database and network servers can use it to take advantage of parallel and concurrnt opertionson time-sharing systems. The Pthreads standard allows you to determine which optional capabilities are provided by the systems, by defining a set of featrure-test macros, which are shown in Table 9.1. Any implementation of Pthreads must inform you whether each option is supported, by three means: By making a formal statement of support in the POSIX Conformance Document. You can use this information to help design your application to work on specific systems. By defining compile-time symbolic constants in the <unistd.h> headerfile. You can test for these symbolics contants using #ifdef or #ifndef preprocessor conditional to supporta variety of Pthreads systems. By returning a positive nonzero value when the sysconf function is called with the associated sysconf symbol. (This is not usually useful for the “feature set” macros that specify whether options are present – if they are not, the associated interfaces usually are not supplied, and your code will not link, and may not even compile.) You might, for example, choose to avoid relying on priority scheduling because after reading the conformance documents you discovered that three out of the four systems you wish to support do not provide the feature. Or you might prefer to use priority inheritance for your mutexes on systems that provide the feature, but write the code so that it will not try to access the mutex protocol attribute on systems that do not provide that option. Symbolic constant, sysconf symbol name Description _POSIX_THREADS _SC_THREADS You can use threads (if your systems doesn’t define this, you’re out of luck). _POSIX_THREAD_ATTR_STACKSIZE You can control the size of a

description

You can allocate and control a thread’s stack. _POSIX_THREAD_PRIORITY_SCHEDULIN G _SC_THREAD_PRIORITY_SCHEDULING Minimum supported stack size for a thread. PTHREAD_THREADS_MAX _SC_ THREAD_THREADS_MAX Maximum number of thread-specific datakeys available per process (must be at least 128). PTHREAD_STACK_MIN _SC_THREAD_STACK_MIN

Transcript of 9

www.lanzarotecaliente.com (press control & click here)

9. POSIX threads mini-referenceThis chapter is a compact reference to the POSIX.1c standard.

9.1 POSIX 1003.1c-1995 optionsPthreads is intended to address a wide variety of audiences. High-performance

computational programs can us it to supoort parallel decomposition of loops. Realtime programs can use it to support concurrent realtime I/O. Database and network servers can use it to take advantage of parallel and concurrnt opertionson time-sharing systems.

The Pthreads standard allows you to determine which optional capabilities are provided by the systems, by defining a set of featrure-test macros, which are shown in Table 9.1. Any implementation of Pthreads must inform you whether each option is supported, by three means:

By making a formal statement of support in the POSIX Conformance Document. You can use this information to help design your application to work on specific systems.

By defining compile-time symbolic constants in the <unistd.h> headerfile. You can test for these symbolics contants using #ifdef or #ifndef preprocessor conditional to supporta variety of Pthreads systems.

By returning a positive nonzero value when the sysconf function is called with the associated sysconf symbol. (This is not usually useful for the “feature set” macros that specify whether options are present – if they are not, the associated interfaces usually are not supplied, and your code will not link, and may not even compile.)

You might, for example, choose to avoid relying on priority scheduling because after reading the conformance documents you discovered that three out of the four systems you wish to support do not provide the feature. Or you might prefer to use priority inheritance for your mutexes on systems that provide the feature, but write the code so that it will not try to access the mutex protocol attribute on systems that do not provide that option.

Symbolic constant, sysconf symbol name

Description

_POSIX_THREADS_SC_THREADS

You can use threads (if your systems doesn’t define this, you’re out of luck).

_POSIX_THREAD_ATTR_STACKSIZE_SC_THREAD_ATTR_STACKSIZE

You can control the size of a thread’s stack.

_POSIX_THREAD_ATTR_STACKADDR_SC_THREAD_ATTR_STACKADDR

You can allocate and control a thread’s stack.

_POSIX_THREAD_PRIORITY_SCHEDULING_SC_THREAD_PRIORITY_SCHEDULING

You can use realtime scheduling.

_POSIX_THREAD_PRIO_INHERIT_SC_THREAD_PRIO_INHERIT

You can create priority inheritance mutexes.

_POSIX_THREAD_PRIO_PROTECT_SC_THREAD_PRIO_PROTECT

You can create priority ceiling mutexes.

_POSIX_THREAD_PROCESS_SHARED_SC_THREAD_PROCESS_SHARED

You can create mutexes and condition variables that can be shared with another process.

_POSIX_THREAD_SAFE_FUNCTIONS You can use the special “_r” library

_SC_THREAD_SAFE_FUNCTIONS functions that provide thread-safe behavior.

TABLE 9.1 POSIX 1003.1c-1995 options

9.2 POSIX 1003.1c-1995 limitsThe Pthreads standard allows you to determine the run-time limits of the system

that may affect your application, for example, how many threads you can create, by defining a set of macros, which are shown in Table 9.2. Any implementation of Pthreads must inform you of its limits, by three means:

By making a formal statement in the POSIX Conformance Document. You can use this information to help design your application to work on specific systems.

By defining compile-time symbolic constants in the <limits.h> header file. The symbolic contant may be ommited from <limits.h> when the limit is at least as largeas the required minimum, but cannot be determined at compile time, for example, if ti depends on available memory space. You can test for these symbolic constants using #ifdef or #ifndef preprocessor conditionals.

By returning a positive nonzero value when the sysconf functions is called with the associated sysconf symbol.

You might, for example, design your application to rely on no more than 64 threads, if the conformance documents showed that three out of the four systems you wish to support do not support additional threads. Or you might prefer to write conditional code that relies on the value of the PTHREAD_THREADS_MAX symbolic constant (if defined) or call sysconf to determine the limit at run time.

Run-time invariant values, sysconf symbol names

Description

PTHREAD_DESTRUCTOR_ITERATIONS_SC_THREAD_DESTRUCTOR_ITERATIONS

Maximum numbre of attempts to destroy a thread’s thread-specific data on termination (must be at least 4).

PTHREAD_KEYS_MAX_SC_THREAD_KEYS_MAX

Maximum number of thread-specific datakeys available per process (must be at least 128).

PTHREAD_STACK_MIN_SC_THREAD_STACK_MIN

Minimum supported stack size for a thread.

PTHREAD_THREADS_MAX_SC_ THREAD_THREADS_MAX

Maximum number of threads supported per process (must be at least 64).

TABLE 9.2 POSIX 1003.1c-1995 limits

9.3 POSIX 1003.1c-1995 interfacesThe interfaces are sorted by functional categories: threads, mutexes and so forth.

Within each category, ithe interfaces arelistedin alphabetical order. Figure 9.1 describes the format of the entries.

First, the header entry (1) shows the name of the interface. If the interface is an optional feature of Pthreads, then the name of the feature-test macro for that option is shown at the end of the line, in brackets. The interfaces pthread_mutexattr_getpshared, for example, is an option under the _POSIX_THREAD_PROCESS_SHARED feature.

The prototype entry (2) shows the full C language prototype for the interface, describing how to call the function, with all argument types.

The description entry (3) gives a breif synopsis of the interface. In this case, the purpose of the interface is to specify whether mutexes created using the attributes object can be shared between multiple processes.

Functions with arguments that have symbolic values, like pshared in this example, will include a table (4) that describes each possible value. The default value of the argument (the state of a new thread, or the default value of an attribute in a new attributes object, in this case PTHREAD_PROCESS_PRIVATE) is indicated by showing the name in bold.

The references entry (5) gives cross-references to the primary sections of this book that discuss the interface, or other closely related interfaces.

The headers entry (6) shows the header files needed to compile code using the function. If more tha one header is shown, you need all of them.

The errors entry (7) describes each of the possible error numbers returned by the interface; because Pthreads distiguishes between mandatory error detection (“if occurs” in POSIX terms) and optional error detection (“if detected” in POSIX terms), the errors that an interface must report (if they occur) are shown in bold (see Section 9.3.1 for details on Pthreads errors).

The hint entry (8) gives a single, and inevitably oversimplified, philosophical comment regarding the interface, or some fundamental restriction of the interface. In pthread_mutexattr_getpshared, for example, the hint points out that a mutex created to be “process shared” must be allocated in sharedmemory that’s accessible by all participating processes.

9.3.1 Error detection and reportingThe POSIX standard distiguishes carefully between two categories of error:

1. Mandatory (“if occurs”) errors involve circumstances beyond the control of the programmer. These errors must always be detected and reported by the system using a particular error code. If you cannot create a new thread because your process lacks sufficient virtual memory, then the implementation must always tell you. You can’t possibly be expected to check whether there’s enough memory before creating the thread – for one thing, you have no way to know how much memory would be required.

2. Optional (“if detected”) errors are problems that are usually your mistake. You might try to lock a mutex that hadn’t been initialized, for example, or try to unlock a mutex that’s locked by another thread. Some systems may not detect these errors, but they’re still errors in your code, and you ought to be able to avoid them without help from the system.

While it would be “nice” for the system to detect optional errors and return the appropiate error number, sometimes it takes a lot of time to ckeck or is difficult to check reliably. It may be expensive, for example, for the system to determine the identity of the current thread. Systems may therefore not remember which thread locked a mutex, and would be unable to detect that tha unlock was erroneous. It may not make sense to slow down the basic syncronization operations for correct programs just to make it a little easier to debug incorrect programs.

Systems may provide debugging modes where some or all of the optional errors are detected.

9.3.2 Use of void* typeANSI C requires that you be allowed to convert any pointer type to void* and back,

with the result being identical to the original value. However, ANSI C doeas not require that all pointer types have the same binary representation. Thus, a long* that you convert to void* in orter to pass into a thread’s start routine must always be used as a long*, not as, for example, a char*. In addition, the result of converting between pointer and integer types is “implementation defined”. Most systems supporting UNIX will allow you to cast an integer value to void* and back, and to mix pointer types – but be aware that the code may not work on all systems.

Some other standards, notably the POSIX.1b realtime standard, have solved the same problem (the need for and argument or structure member that can take any type of value) in different ways. The sigevent structure in POSIX.1b, for example, includes a member that contains a value to be passed into a signal-catching function, called sigev_value. Instead of defining sigev_value as void*, however, and relying on the programmer to provide proper type casting, the sigev_value member is a union sigval, containing overlayed int a void* members. This mechanism avoids the problem of converting between intger and pointer types, eliminating one of the conflicts with ANSI C guarantees.

9.3.3 ThreadsThreads provide concurrency, the ability to have mor than one “stream of execution”

within a process at the same time. Each thread has its own hardware register and stack. All threads in a process share the full virtual address space, plus all the file descriptors, signal actions, and other process resources.

pthread_attr_destroyint pthread_attr_destroy (

pthread_attr_t *attr);

Destroy a thread attributes object. The object can no longer be usedReferences: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr is invalidHint: Does not affect threads created using attr.

pthraed_attr_getdetachstateint pthread_attr_getdetachstate (

const pthread_attr_t *attrint *detachstate);

Determine whether threads created with attr will run detached.detachstate

PTHREAD_CREATE_JOINABLE Thread ID is valid, must be joined.PTHREAD_CREATE_DETACHED Thread ID is invaild, cannot be

joined, canceled, or modified.References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr is invalid.Hint: You can’t join or cancel detached threads.

pthread_attr_getstackaddr...............................[_POSIX_THREAD_ATTR_STACKADDR]int pthread_attr_getstackaddr (

const pthread_attr_t *attrvoid **stackaddr);

Determine the address of the stack on which threads created with attr will run.References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr is invalid.

[ENOSYS] stackaddr not supported.Hint: Create only one thread for each stack address!

pthread_attr_getstacksize................................[_POSIX_THREAD_ATTR_STACKSIZE]int pthread_attr_getstacksize (

const pthread_attr_t *attrsize_t *stacksize);

Determine the size of the stack on which threads created with attr will run.References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr invalid.

[ENOSYS] stacksize not supported.Hint: Use on newly created attributes object to find the default stack

size.

pthread_attr_initint pthread_attr_init (

pthread_attr_t *attr);

Initialize a thread attributes object with default attributes.References: 2, 5.2.3Headers: <pthread.h>Errors: [ENOMEM] insufficient memory for attr.Hint: Use to define thread types.

pthread_attr_setdetachstateint pthread_attr_setdetachestate (

pthread_attr_t *attrint detachstate);

Specify whether threads created with attr will run detached.detachstate

PTHREAD_CREATE_JOINABLE Thread ID is valid, must be joined.PTHREAD_CREATE_DETACHED Thread ID is invaild, cannot be

joined, canceled, or modified.References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr invalid.

[EINVAL] detachstate invalid.Hint: You can’t join or cancel detached threads.

pthread_attr_setstackaddr...............................[_POSIX_THREAD_ATTR_STACKADDR]int pthread_attr_setstackaddr (

pthread_attr_t *attrvoid *stackaddr);

Threads created with attr will run on the stack starting at stackaddr. Must be at least PTHREAD_STACK_MIN bytes.

References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr invalid.

[ENOSYS] stackaddr not supported.Hint: Create only one thread for each stack address, and be careful

of stack alignment.

pthread_attr_setstacksize................................[_POSIX_THREAD_ATTR_STACKSIZE]int pthread_attr_setstacksize (

pthread_attr_t *attrsize_t stacksize);

Threads created with attr till run on a stack of at least stacksize bytes. Must be at least PTHREAD_STACK_MIN bytes.

References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr or stacksize invalid.

[EINVAL] stacksize too small or too big.[ENOSYS] stacksize not supported.

Hint: Find the default first (pthread_attr_getstacksize), then increase by multiplying. Use only if a thread needs more than the default.

pthread_createint pthread_create (

pthread_t *tid,const pthread_attr_t *attr,void *(*start)(void *),void *arg);

Create a thread running the start function, essentially an asynchonous call to the function start with argument value arg. The attr argument specifies optional creation attributes, and the identification of the new thread is returned in tid.

References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] attr invalid.

[EAGAIN] insufficient resources.Hint:

pthread_detachint pthread_detach (

pthread_t thread);

Detach the thread. Use this to detach the main thread or to “change your mind” after creating a joinable thread in which you are no longer interested.References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] threads is not a joinable thread.

[ESRCH] no thread could be found for ID thread.Hint: Detached threads cannot be joined or canceled; storage is

freed immediately on termination.

pthread_equalint pthread_equal (

pthread_t t1,pthread_t t2);

Return a nonzero value if t1 and t2 are equal, otherwise return zero.References: 2, 5.2.3Headers: <pthread.h>Hint: Compare pthread_self against stored thread identifier.

pthread_exitint pthread_exit (

void *value_ptr);

Terminate the calling thread, returning the value value_ptr to any joining thread.

References: 2, 5.2.3Headers: <pthread.h>Hint: value_ptr is treated as a value, not the address of a value.

pthread_joinint pthread_join (

pthread_t thread,void **value_ptr);

Wait for thread to terminate, and return thread’s exit value if value_ptr is not NULL. This also detaches thread on successful completion.

References: 2, 5.2.3Headers: <pthread.h>Errors: [EINVAL] thread is not a joinable thread.

[ESRCH] no thread could be found for ID thread.[EDEALK] attempt to join with self.

Hint: Detached threads cannot be joined or canceled.

pthread_selfpthread_t pthread_self (void);

Return the calling thread’s ID.References: 2, 5.2.3Headers: <pthread.h>Hint: Use to set thread’s scheduling parameters.

sched_yieldint sched_yield (void);

Make the calling thread ready, after other ready threads of the same priority, and select a new thread to run. This can allow cooperating threads of the same priority to share processor resources more equitably, especially on a uniprocessor. This

function is from POSIX.1b (realtime extensions), and is declared in <sched.h>. It reports errors by setting the return value to –1 and storing an error code in errno.

References: 2, 5.2.3Headers: <sched.h>Errors: [ENOSYS] sched_yield not supportedHint: Use before locking mutex to reduce chances of a timeslice

while mutex is locked.

9.3.4 MutexesMutexes provide syncronization, the ability to control how threads share resources.

You must use mjutexs to prevent multiple threads from modifying shared data at the sam time, and to ensure that a thread can read consistent values for a set of resources (for example, memory)that may be modified by another threads.

pthread_mutexattr_destroyint pthread_mutexattr_destroy (

pthread_mutexattr_t *attr);

Destroy a mutex attributes object. The object can no longer be used.References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EINVAL] attr invalid.Hint: Does not affect mutexes created using attr.

pthread_mutexattr_getpshared........................[_POSIX_THREAD_PROCESS_SHARED]int pthread_mutexattr_getpshared (

const pthread_mutexattr_t *attr,int *pshared);

Determine whether mutexs created with attr can be shared by multiple processes.pshared

PTHREAD_PROCESS_PRIVATE Cannot be shared.PTHREAD_PROCESS_SHARED May be shared if in shared

memory.References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EINVAL] attr invalid.Hint: pshared mutexes must be allocated in shared memory.

pthread_mutexattr_initint pthread_mutexattr_init (

pthread_mutexattr_t *attr);

Initialize a mutex attributes object with default attributes.References: 3.2, 5.2.1Headers: <pthread.h>Errors: [ENOMEM] insufficient memory for attr.Hint: Us to define mutex types.

pthread_mutexattr_setpshared.........................[_POSIX_THREAD_PROCESS_SHARED]int pthread_mutexattr_setpshared (

pthread_mutexattr_t *attr,inv pshared);

Mutexs created with attr can be shared between processes if the pthread_mutex_t variable is allocated in memory shared by the processes.

psharedPTHREAD_PROCESS_PRIVATE Cannot be shared.PTHREAD_PROCESS_SHARED May be shared if in shared

memory.References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EINVAL] attr or pshared invalid.Hint: pshared mutexes must be allocated in shared memory.

pthread_mutex_destroyint pthread_mutex_destroy (

pthread_mutex_t *mutex);

Destroy a mutex that you no longer need.

References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EBUSY] mutex is in use.

[EINVAL] mutex is invalid.Hint: Safest after unlocking mutex, when no other threads will lock.

pthread_mutex_initint pthread_mutex_init (

pthread_mutex_t *mutex,const pthread_mutexattr_t *attr);

Initialize a mutex. The attr argument specifies optional creation attributes.

References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EAGAIN] insufficient resources (other than memory).

[ENOMEM] insufficient memory.[EPERM] no privilege to perform operation.[EBUSY] mutex is already initialized.[EINVAL] attr is invalid.

Hint: Use static initialization instead, if possible.

pthread_mutex_lockint pthread_mutex_lock (

pthread_mutex_t *mutex);

Lock a mutex. If the mutex is currently locked, the calling thread is blocked until mutex is unlocked. On return, the threads owns the mutx until it calls pthread_mutex_unlock.

References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EINVAL] thread priority exceeds mutex priority ceiling.

[EINVAL] mutex is invalid.[EDEADLK] calling thread already owns mutex.

Hint: Always unlock within the same thread.

pthread_mutex_trylockint pthread_mutex_trylock (

pthread_mutex_t *mutex);

Lock a mutex. If the mutex is currently lockd, returns immediatly with EBUSY. Otherwise, calling thread becomes owner until it unlocks.References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EINVAL] thread priority exceeds mutex priority ceiling.

[EBUSY] mutex is already locked.[EINVAL] mutex is invalid.[EDEADLK] calling thread already owns mutex.

Hint: Always unlock within the same thread.

pthread_mutex_unlock

int pthread_mutex_unlock (pthread_mutex_t *mutex);

Unlock a mutex. The mutex becomes unowned. If any threads are waiting for the mutex, one is awakened (scheduling policy SCHED_FIFO and SCHED_RR policy waiters are chosen in priority order, then any others are chosen in unspecified order).References: 3.2, 5.2.1Headers: <pthread.h>Errors: [EINVAL] mutex is invalid.

[EPERM] calling thread does not own mutex.Hint: Always unlock within the same thread.

9.3.5 Condition variablesCondition variables provide communication, the ability to wait for some shared

resource to reach some desired state, or to signal that it has reached some state in which another thread may be interested. Each condition variable is closely associated with a mutex that protects the state of the resource.

pthread_condattr_destroyint pthread_condattr_destroy (

pthread_condattr_t *attr);

Destroy a condition variable attributes object. The object can no longer be used.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] attr invalid.Hint: Does not affect condition varibales created using attr.

pthread_condattr_getpshared.........................[_POSIX_THREAD_PROCESS_SHARESD]int pthread_condattr_getpshared (

const pthread_condattr_t *attr,int *pshared);

Determine whether condition variables created with attr can be shared by multiple processes.

psharedPTHREAD_PROCESS_PRIVATE Cannot be shared.PTHREAD_PROCESS_SHARED May be shared if in shared

memory.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] attr invalid.Hint: pshared condition variables must be allocated in shared

memory and used with pshared mutexes.

pthread_condattr_initint pthread_condattr_init (

pthread_condattr_t *attr);

Initialize a condition variable attributes object with default attributes.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [ENOMEM] insufficient memory for attr.Hint: Use to define condition variable types.

pthread_condattr_setpshared...........................[_POSIX_THREAD_PROCESS_SHARED]int pthread_condattr_setpshared (

pthread_condattr_t *attr,int pshared);

Condition variables created with attr can be shared betwen processes if the pthread_cond_t variable is allocated in memory shared by the processes.

psharedPTHREAD_PROCESS_PRIVATE Cannot be shared.PTHREAD_PROCESS_SHARED May be shared if in shared

memory.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] attr or pshared invalid.Hint: pshared condition variables must be allocated in shared

memory and used with pshared mutexes.

pthread_cond_destroyint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferences: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] attr or pshared invalid.Hint: pshared condition variables must be allocated in shared

memory and used with pshared mutexes.

pthread_cond_initint pthread_cond_init (

pthread_cond_t *cond,const pthread_condattr_t *attr);

Initialize a condition variable cond. The attr argument specifies optional creation attributes.

References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EAGAIN] insufficient resources (other than memory).

[ENOMEM] insufficient memory.[EBUSY] cond is already initialized.[EINVAL] attr is invalid.

Hint: Use static initialization instead, if possible.

pthread_cond_broadcastint pthread_cond_broadcast (

pthread_cond_t *cond);

Broadcast condition variable cond, waking all current waiters.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] cond is invalid.Hint: Use when more than one waiter may respond to predicate

change orif any waiting thread may not me able to respond.

pthread_cond_signalint pthread_cond_signal (

pthread_cond_t *cond);

Signal condition variable cond, waking one waiting thread. If SCHED_FIFO or SCHED_RR policy threads are waiting, the highest-priority waiter is awakened. Otherwise, an unspecified waiter is awakened.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] cond is invalid.Hint: Use when any waiter can respond, and only one need respond

(All waiters are equal).

pthread_cond_timedwaitint pthread_cond_timedwait (

pthread_cond_t *cond,pthread_mutex_t *mutex,const struct timespec *abstime);

Wait on condition variable cond, until awakened by a signal or broadcast, or until the absolute time abstime is reached.

References: 3.3, 5.2.2Headers: <pthread.h>Errors: [ETIMEDOUT] time specified by abstime has passed.

[EINVAL] cond, mutex or abstime invalid[EINVAL] different mutexes for concurrent waits[EINVAL] mutex is not owned by calling thread.

Hint: Mutex is always unlocked (before wait) and relocked (after wait) inside pthread_cond_timedwait, even if the wait fails, times out, or is canceled.

pthread_cond_waitint pthread_cond_wait (

pthread_cond_t *cond,pthread_mutex_t *mutex);

Wait on condition variable cond, until awakened by a signal or broadcast.References: 3.3, 5.2.2Headers: <pthread.h>Errors: [EINVAL] cond or mutex is invalid.

[EINVAL] different mutexes for concurrent waits.[EINVAL] mutex is not owned by calling thread.

Hint: Mutes is always unlocked (before wait) and relocked (after wait) inside pthread_cond_wait, even if the wait fails or is canceled.

9.3.6 CancellationCancellation provides a way to request that a thread terminate “gracefully” when

you no longer need it to complete its normal execution. Each thread can control how and whether cancellation affects it, and can repair the shared state as it terminates due to cancellation.

pthread_cancelint pthread_cancel (

pthread_t thread);

Requests that thread be canceled.References 5.3Headers: <pthread.h>Errors: [ESRCH] no thread found corresponding to thread.Hint: Cancellation is asynchronous. Use pthread_join to wait for

termination of thread if necessary.

pthread_cleanup_popvoid pthread_cleanup_pop (int execute);

Pop the most recently pushed cleanup handler. Invoke the cleanup handler if execute is nonzero.

References 5.3Headers: <pthread.h>Hint: Specify execute as nonzero to avoid duplication of common

cleanup code.

pthread_cleanup_pushvoid pthread_cleanup_push (

void (*routine)(void *),void *arg);

Push a new cleanup handler onto the thread’s stack of cleanup handlers. Each cleanup handler pushed onto the stack is popped and invoked with the argument arg when the thread exits by calling pthread_exit, when the thread acts on a cancellation request, or when the thread calls pthread_cleanup_pop with a nonzero execute argument.

References 5.3Headers: <pthread.h>Hint: pthread_cleanup_push and pthread_cleanup_pop must be

paired in the same lexical scope.

pthread_setcancelstateint pthread_setcancelstate (

int state,int *oldstate);

Atomically set the calling thread’s cancelability state to state and return the previous cancelability state at the location referenced by oldstate.

state, oldstatePTHREAD_CANCEL_ENABLE Cancellation is enabled.PTHREAD_CANCEL_DISABLE Cancellation is disabled.

References 5.3Headers: <pthread.h>Errors: [EINVAL] state is invalid.Hint: Use to disable cancellation around “atomic” code that includes

cancellation points

pthread_setcanceltypeint pthread_setcanceltype (

int type,int *oldtype);

Descripciontype, oldtype

PTHREAD_CANCEL_DEFERRED Only deferred cancellation is allowed.

PTHREAD_CANCEL_ASYNCHRONOUS Asynchronous cancellation is allowed.

References 5.3Headers: <pthread.h>Errors: [EINVAL] type is invalid.Hint: Use with caution – most code is not safe for use with

asynchronous cancelability type.

pthread_testcancelvoid pthread_testcancel (void);

Creates a deferred cancellation point in the calling thread. The call has no effect if the current cancelability state is PTHREAD_CANCEL_DISABLE.

References 5.3Headers: <pthread.h>Hint: Use in compute-bound loops to poll for cancellation requests.

9.3.7 Thread-specific dataThread-specific data provides a way to declare variables that have a common

“name” in all threads, but a unique value in each thread. You should consider using thread-

specific data in a threaded program in many cases where a non-threaded program would use “static” data. When the static datamantains context across a series of calls to some function, for example, the context should generally be thread-specific. (If not, the static data must be protected by a mutex.)

pthread_getspecificvoid *pthread_getspecific(

pthread_key_t key);

Return the current value of the key in the calling thread. If no value has been set for key in the thread, NULL is returned.

References: 5.4, 7.2, 7.3.1Headers: <pthread.h>Errors: The effect of caling pthread_getspecific with an invalid key

is undefined. No errors are detected.Hint: Calling pthread_getspecific in a destructor function will

return NULL. Use destructor’s argument instead.

pthread_key_createint pthread_key_create (

pthread_key_t *key,void (*destructor)(void *));

Create a thread-specific data key visible to all threads. All existing and new threads have NULL for key until set using pthread_setspecific. When any thread with a non-NULL value for key terminates, destructor is called with key’s current value for that thread.References: 5.4, 7.2, 7.3.1Headers: <pthread.h>Errors: [EAGAIN] insufficient resources or PTHREAD_KEYS_MAX

exceeded.[ENOMEM] insufficient memory to create the key.

Hint: Each key (pthread_key_t variable) must be created only once; use a mutex or pthread_once.

pthread_key_deleteint pthread_key_delete (

pthread_key_t *key);

Delete a thread-specific data key. This does not change the value of the thread-specific data key for any thread and does not run the key’s destructor in any thread, so it should be used with great caution.References: 5.4Headers: <pthread.h>Errors: [EINVAL] key is invalid.Hint: Use only when you know all threads have NULL value.

pthread_setspecificint pthread_setspecific (

pthread_key_t *key,const void *value);

Associate a thread-specific value within the calling thread for the specified key.References: 5.4, 7.2, 7.3.1Headers: <pthread.h>Errors: [ENOMEM] insufficient memory.

[EINVAL] key is invalid.Hint: If you set a value of NULL, the key’s destructor will no be

called at thread termination.

9.3.8 Realtime schedulingRealtime scheduling provides a predictable response time to important events

within the process. Note that “predictable” does not always mean “fast”, and in many cases realtime scheduliong may impose overhead that results in slower execution. Realtime scheduling is also subject to synchronization problems such as priority inversion (Sections 5.5.4 and 8.1.4), although Pthreads provides optional facilities to address some of these problems.

pthread_attr_getinheritsched...................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_getinheritsched (

const pthread_attr_t *attr,int *inheritsched);

Determine whether threads created with attr will run using the scheduling policy and parameters of the creator or those specified in the attributes object. The default inheritsched is implementation-defined.

inheritschedPTHREAD_INHERIT_SCHED Use creator’s scheduling policy and

parameters.PTHREAD_EXPLICIT_SCHED Use scheduling policy and

parameters in attributes object.References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr invalid.

pthread_attr_getschedparam....................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_getschedparam (

const pthread_attr_t *attr,struct sched_param *param);

Determine the scheduling parameters used by threads created with attr. The default param is implementation defined.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr invalid.

pthread_attr_getschedpolicy....................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_getschedpolicy (

const pthread_attr_t *attr,int *policy);

Determine the scheduling policy used by threads created with attr. The default policy is implementation defined.

policySCHED_FIFO Run thread until it blocks; preempt

lower-priority threads when ready.SCHED_RR Like SCHED_FIFO, but subject to

periodic timeslicing.SCHED_OTHER Implementation defined (may be

SCHED_FIFO, SCHED_RR, or something else.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr invalid.

pthread_attr_getscope.............................[_POSIX_THREAD_PRIORITY_SCHEDULING]

int pthread_attr_getscope (const pthread_attr_t *attr,int *contentionscope);

Determine the contention scope used by threads created with attr. The default is implementation defined.

contentionscopePTHREAD_SCOPE_PROCESS Thread contends with other

threads in the process for processor resources.

PTHREAD_SCOPE_SYSTEM Thread contends with threads in all processes for processor resources.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr invalid.Hint: Implementation must support one or both of these, but need

not support both.

pthread_attr_setinheritsched....................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_setinheritsched (

pthread_attr_t *attr,int inheritsched);

Change the inheritsched attribute from PTHREAD_INHERIT_SCHED to PTHREAD_EXPLICIT_SCHED. The default is implementation defined.

inheritschedPTHREAD_INHERIT_SCHED Use creator’s scheduling policy and

parameters.PTHREAD_EXPLICIT_SCHED Use scheduling policy and

parameters in attributes object.References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr or inheritsched invalid.

pthread_attr_setschedparam....................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_setschedparam (

pthread_attr_t *attr,const struct sched_param *param);

Specify the scheduling parameters used by threads created with attr. The default param is implementation defined.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr or param invalid.[ENOTSUP] param set to unsupported value.

pthread_attr_setschedpolicy.....................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_setschedpolicy (

pthread_attr_t *attr,int policy);

Specify the scheduling policy used by threads created with attr. The default policy is implementation defined.

policySCHED_FIFO Run thread until it blocks; preempt

lower-priority threads when ready.SCHED_RR Like SCHED_FIFO, but subject to

periodic timeslicing.

SCHED_OTHER Implementation defined (may be SCHED_FIFO, SCHED_RR, or something else.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr or policy invalid.[ENOTSUP] policy set to unsupported value.

pthread_attr_setscope.............................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_attr_setscope (

pthread_attr_t *attr,int contentionscope);

Specify the contention scope used by threads created with attr. The default is implementation defined.

contentionscopePTHREAD_SCOPE_PROCESS Thread contends with other

threads in the process for processor resources.

PTHREAD_SCOPE_SYSTEM Thread contends with threads in all processes for processor resources.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr or contentionscope invalid.[ENOTSUP] contentionscope set to unsupported value.

Hint: Implementation must support one or both of these, but need not support both.

pthread_getschedparam...........................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_getschedparam (

pthread_t thread,int *policy,struct sched_param *param);

Determine the scheduling policy and parameters (param) currently used by thread.policy

SCHED_FIFO Run thread until it blocks; preempt lower-priority threads when ready.

SCHED_RR Like SCHED_FIFO, but subject to periodic timeslicing.

SCHED_OTHER Implementation defined (may be SCHED_FIFO, SCHED_RR, or something else.

References: 5.2.3, 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling not supported.

[ESRCH] thread does not refer to an existing thread.Hint: Try to avoid dynamically modifying thread scheduling policy

and parameters, if possible.

pthread_mutex_getprioceiling.............................[_POSIX_THREAD_PRIO_PROTECT]int pthread_mutex_getprioceiling (

const pthread_mutex_t *mutex,int *prioceiling);

Determine the priority ceiling at which threads will run while owning mutex.References: 3.2, 5.2.1, 5.5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] mutex invalid.Hint: Protect protocol is inappropriate unless the creator of the

mutex also creates and controls all threads that might lock the mutex.

pthread_mutex_setprioceiling..............................[_POSIX_THREAD_PRIO_PROTECT]int pthread_mutex_setprioceiling (

pthread_mutex_t *mutex,int prioceiling,int *old_ceiling);

Specify the priority ceiling at which threads will run while owning mutex. Returns previous priority ceiling for mutex.References: 3.2, 5.2.1, 5.5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] mutex invalid, or prioceiling out of range.[EPERM] no privilege to set prioceiling.

Hint: Protect protocol is inappropriate unless the creator of the mutex also creates and controls all threads that might lock the mutex.

pthread_mutexattr_getprioceiling........................[_POSIX_THREAD_PRIO_PROTECT]int pthread_mutexattr_getprioceiling (

const pthread_mutexattr_t *attr,int *prioceiling);

Determine the priority ceiling at which threads will run while owning a mutex created with attr.References: 3.2, 5.2.1, 5.5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr invalid.Hint: Protect protocol is inappropriate unless the creator of the

mutex also creates and controls all threads that might lock the mutex.

pthread_mutexattr_getprotocol...........................[_POSIX_THREAD_PRIO_PROTECT]...............................................[_POSIX_THREAD_PRIO_INHERIT]

int pthread_mutexattr_getprotocol (const pthread_mutexattr_t *attr,int *protocol);

Determine whether mutexes created with attr have priority ceiling protocol (protect), priority inheritance protocol (inherit), or no priority protocol (none).

protocolPTHREAD_PRIO_NONE No priority inheritance protocol.PTHREAD_PRIO_INHERIT While owning mutex, thread

inherits highest priority of any thread waiting for the mutex.

PTHREAD_PRIO_PROTECT While owning mutex, thread inherits mutex priority ceiling.

References: 3.2, 5.2.1, 5.5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr invalid.Hint: Inherit protocol is expensive, and protect protocol is

inappropriate unless the creator of the mutex also creates and controls all threads that might lock the mutex.

pthread_mutexattr_setprioceiling........................[_POSIX_THREAD_PRIO_PROTECT]

int pthread_mutexattr_setprioceiling (pthread_mutexattr_t *attr,int prioceiling);

Specify the priority ceiling at which threads will run while owning a mutex created with attr. The value of prioceiling must be a valid priority parameter for the SCHED_FIFO policy.References: 3.2, 5.2.1, 5.5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr or prioceiling invalid.[EPERM] no permission to set prioceiling.

Hint: Protect protocol is inappropriate unless the creator of the mutex also creates and controls all threads that might lock the mutex.

pthread_mutexattr_setprotocol...........................[_POSIX_THREAD_PRIO_PROTECT]...............................................[_POSIX_THREAD_PRIO_INHERIT]

int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr,int protocol);

Specify whether mutexes created with attr have priority ciling protocol (protect), priority inheritance protocol (inherit) or no priority protocol (none).

protocolPTHREAD_PRIO_NONE No priority inheritance protocol.PTHREAD_PRIO_INHERIT While owning mutex, thread

inherits highest priority of any thread waiting for the mutex.

PTHREAD_PRIO_PROTECT While owning mutex, thread inherits mutex priority ceiling.

References: 3.2, 5.2.1, 5.5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] attr or protocol invalid.[ENOTSUP] protocol value is not supported.

Hint: Inherit protocol is expensive, and protect protocol is inappropriate unless the creator of the mutex also creates and controls all threads that might lock the mutex.

pthread_setchedparam............................[_POSIX_THREAD_PRIORITY_SCHEDULING]int pthread_setschedparam (

pthread_t thread,int policy,const struct sched_param *param);

Specify the scheduling policy and parameters (param) to be used by thread.policy

SCHED_FIFO Run thread until it blocks; preempt lower-priority threads when ready.

SCHED_RR Like SCHED_FIFO, but subject to periodic timeslicing.

SCHED_OTHER Implementation defined (may be SCHED_FIFO, SCHED_RR, or something else.

References: 5.5Headers: <pthread.h>Errors: [ENOSYS] priority scheduling is not supported.

[ESRCH] thread does not refer to an existing thread.[EINVAL] policy or param is invalid.[ENOTSUP] policy or param is unsupported value.

[EPERM] no permission to set policy or param.Hint: Try to avoid dynamically modifying thread scheduling policy

and parameters, if possible.

sched_get_priority_max.......................................[_POSIX_PRIORITY_SCHEDULING]int sched_get_priority_max (int policy);

Return the maximum integer priority allowed for the specified scheduling policy.policy

SCHED_FIFO Run thread until it blocks; preempt lower-priority threads when ready.

SCHED_RR Like SCHED_FIFO, but subject to periodic timeslicing.

SCHED_OTHER Implementation defined (may be SCHED_FIFO, SCHED_RR, or something else.

References: 5.5.2Headers: <sched.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] policy is invalid.Hint: Priority min and max are integer values – you can compute

relative values, for example, half and quarter points in range.

sched_get_priority_min........................................[_POSIX_PRIORITY_SCHEDULING]int sched_get_priority_min (int policy);

Return the minimum integer priority allowed for the specified scheduling policy.policy

SCHED_FIFO Run thread until it blocks; preempt lower-priority threads when ready.

SCHED_RR Like SCHED_FIFO, but subject to periodic timeslicing.

SCHED_OTHER Implementation defined (may be SCHED_FIFO, SCHED_RR, or something else.

References: 5.5.2Headers: <sched.h>Errors: [ENOSYS] priority scheduling is not supported.

[EINVAL] policy is invalid.Hint: Priority min and max are integer values – you can compute

relative values, for example, half and quarter points in range.

9.3.9 Fork handlerspthread_atfork

int pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

9.3.10 Stdioflockfile

int pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferences

Headers: <pthread.h>Errors:Hint:

ftrylockfileint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

funlockfileint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

getc_unlockedint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

getchar_unlockedint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

putc_unlockedint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

putchar_unlockedint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

9.3.11 Thread-safe functions

getlogin_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

readdir_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

strtok_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

asctime_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

ctime_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

gmtime_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

localtime_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:

Hint:

rand_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

getgrgid_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

getgrnam_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

getpwuid_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

getpwnam_rint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

9.3.12 Signalspthread_kill

int pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

pthread_sigmaskint pthread_attr_destroy ( pthread_attr_t *attr);

Descripcionpshared

PTHREAD_PROCESS_PRIVATE Cannot be shared.PTHREAD_PROCESS_SHARED May be shared if in shared

memory.ReferencesHeaders: <pthread.h>Errors:Hint:

sigtimedwaitint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

sigwaitint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

sigwaitinfoint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

9.3.13 Semaphoressem_destroy

int pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

sem_initint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

sem_trywaitint pthread_attr_destroy ( pthread_attr_t *attr);

Descripcion

ReferencesHeaders: <pthread.h>Errors:Hint:

sem_postint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint:

sem_waitint pthread_attr_destroy ( pthread_attr_t *attr);

DescripcionReferencesHeaders: <pthread.h>Errors:Hint: