What is UNIX

UNIX® System Threads Reference

1. Introduction

All source that uses threads must include the header

#include <pthread.h>

Name Space

Each threads type is of the form:

pthread[_object]_t

Each threads function (apart from pread(),pwrite() and sigwait()) has the form

pthread[_object]_operation

where object is a type (not required if object is a thread), and operation is a type-specific operation.

All threads functions (except for pread(), pthread_exit(), pthread_getspecific(), pthread_self() and pwrite()) return zero (0) for success and non-zero on failure. The non-zero failure value is an error number to indicate the cause of the error (see errno.h).

.

Threads Types

There are ten (10) threads types.

Type
Description
pthread_attr_t Used to identify a thread attributes object.
pthread_cond_t Used for condition variables.
pthread_condattr_t Used to identify a condition attribute object.
pthread_key_t Used for thread-specific data (TSD) keys.
pthread_mutex_t Used for mutexes (mutual excusion lock)
pthread_mutexattr_t Used to identify a mutex attribute object.
pthread_once_t Used for once-only initialisation.
pthread_rwlock_t Used for read-write locks.
pthread_rwlockattr_t Used for read-write lock attributes.
pthread_t Used to identify a thread

.

2. UNIX System Threads API

pthread_atfork
Synopsisint pthread_atfork ( void (*prepare) (void), void (*parent)(void), void (*child) (void));
DescriptionRegister functions to be called during fork() execution
ErrorsENOMEM
Notesprepare functions are called in reverse order of registration. parent and child functions are called in order of registration

.

Threads Attributes

All threads attributes are set in a thread attributes object by a function of the form:

int pthread_attr_setname( pthread_attr_t *attr, Type t);

All threads attributes are retrieved from a threads attributes object by a function of the form:

int pthread_attr_getname( pthread_attr_t *attr, Type t);

Where name and Type are from the table below:
Type and NameDescription and Value(s)
size_t stacksizeThe thread's stack size. >= PTHREAD_STACK_MIN
void *stackaddrThe thread's stack address. For example, void *stack
size_t guardsizeThe thread's stack guard size. The default size is PAGESIZE bytes.
int detachstate The thread's detach state:

PTHREAD_CREATE_DETACHED,PTHREAD_CREATE_JOINABLE

int contentionscopeThe thread's scope.

PTHREAD_SCOPE_SYSTEM, PTHREAD_SCOPE_PROCESS

int inheritschedThe thread's scheduling inheritence PTHREAD_INHERIT_SCHED,PTHREAD_EXPLICIT_SCHED
int schedpolicyThe thread's scheduling policy.

SCHED_FIFO, SCHED_RR, SCHED_OTHER

struct sched_param schedparamThe thread's scheduling parameters.

See POSIX.1 Section 13


pthread_attr_init
Synopsisint pthread_attr_init (pthread_attr_t *attr);
DescriptionInitialize a thread attributes object.
ErrorsENOMEM

pthread_attr_destroy
Synopsisint pthread_attr_destroy(pthread_attr_t *attr);
DescriptionDestroy a thread attributes object
ErrorsNone

The other attribute related functions are listed below:

int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);

int pthread_attr_getguardsize(const pthread_attr_t *attr, size_t *guardsize);

int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched);

int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param);

int pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy);

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

int pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr);

int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize);

int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);

int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);

int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);

int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param);

int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);

int pthread_attr_setscope(pthread_attr_t *attr, int contentionscope);

int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr);

int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);

Thread Management

pthread_create
Synopsisint pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*entry)(void*), void *arg);
DescriptionCreate a new thread of execution
ErrorsEAGAIN, EINVAL
NotesMaximum number of PTHREADS_THREADS_MAX per process

pthread_detach
Synopsisint pthread_detach(pthread_t thread);
DescriptionSet the detachstate of the specified thread to PTHREAD_CREATE_DETACHED
ErrorsEINVAL,ESRCH

pthread_safe
Synopsispthread_t pthread_self(void);
DescriptionReturn the thread ID of the calling thread
Errors None


pthread_equal
Synopsisint pthread_equal(pthread_t thread1, pthread_t thread2);
DescriptionCompare two thread Ids for equality
ErrorsNone

pthread_exit
Synopsisvoid pthread_exit(void *status);
DescriptionTerminate the calling thread
ErrorsNone

pthread_join
Synopsisint pthread_join(pthread_t thread, void **status);
DescriptionSynchronize with the termination of a thread
ErrorsEINVAL,ESRCH,EDEADLK
NotesThis function is a cancellation point

pthread_getschedparam
Synopsis#include <sched.h>

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

DescriptionGet the scheduling policy and parameters of the specified thread
ErrorsENOSYS,ESRCH
NotesDependent on support of _XOPEN_REALTIME_THREADS

pthread_setschedparam
Synopsis#include <sched.h>

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

DescriptionSet the scheduling policy and parameters of the specified thread
ErrorsENOSYS,EINVAL,ENOTSUP,EPERM,ESRCH
NotesDependent on support of _XOPEN_REALTIME_THREADS

Mutex Attributes

All mutex attributes are set in a mutex attribute object by a function of the form:

int pthread_mutexattr_setname(pthread_attr_t *attr, Type t);

All mutex attributes are retrieved from a mutex attribute object by a function of the form:

int pthread_mutexattr_getname(const pthread_attr_t *attr, Type *t);

where name and Type are defined as in the table below:
Type and NameDescription and Value(s)
int protocolDefine the scheduling classes for mutex locks PTHREAD_PRIO_NONE,PTHREAD_PRIO_PROTECT,

PTHREAD_PRIO_INHERIT

int psharedDefines whether a mutex is shared with other processes. PTHREAD_PROCESS_SHARED, PTHREAD_PROCESS_PRIVATE
int prioceilingUsed for mutex attribute priority ceiling values. See POSIX.1 section 13
int typeApplication defined mutex locking

PTHREAD_MUTEX_NORMAL,PTHREAD_MUTEX_RECURSIVE,
PTHREAD_MUTEX_ERRORCHECK,PTHREAD_MUTEX_DEFAULT


pthread_mutexattr_init
Synopsisint pthread_mutexattr_init(pthread_mutexattr_t *attr);
DescriptionInitialize a mutex attribute object
ErrorsENOMEM

pthread_mutexattr_destroy
Synopsisint pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
DescriptionDestroy a mutex attribute object
ErrorsEINVAL

The mutex attribute manipulation routines supported are as follows:

int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr, int *prioceling);

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

int pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr, int *pshared);

int pthread_mutexattr_gettype(pthread_mutexattr_t *attr, int *type);

int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling);

int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol);

int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);

int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);

Mutex Usage

pthread_mutex_init
Synopsisint pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
DescriptionInitialize a mutex
ErrorsEAGAIN,ENOMEM,EPERM,EBUSY,EINVAL

pthread_mutex_destroy
Synopsisint pthread_mutex_destroy(pthread_mutex_t *mutex);
DescriptionDestroy a mutex
ErrorsEBUSY,EINVAL

pthread_mutex_getprioceiling
Synopsisint pthread_mutex_getprioceiling(const pthread_mutex_t *mutex, int *prioceiling);
DescriptionGet the prioceiling value of the specified mutex
ErrorsENOSYS, EINVAL,EPERM
NotesThis is dependent on _XOPEN_REALTIME_THREADS

pthread_mutex_setprioceiling
Synopsisint pthread_mutex_setprioceiling(pthread_mutex_t *mutex, int prioceiling, int *old_ceiling);
DescriptionSet the prioceiling value and return the old prioceiling value in the specified mutex
ErrorsENOSYS,EINVAL,EPERM
NotesThis is dependent on _XOPEN_REALTIME_THREADS

pthread_mutex_lock
Synopsisint pthread_mutex_lock(pthread_mutex_t *mutex);
DescriptionAcquire the indicated mutex
ErrorsEINVAL,EDEADLK

pthread_mutex_trylock
Synopsisint pthread_mutex_trylock(pthread_mutex_t *mutex);
DescriptionAttempt to acquire the indicated mutex
ErrorsEINVAL,EBUSY

pthread_mutex_unlock
Synopsisint pthread_mutex_unlock(pthread_mutex_t *mutex);
DescriptionRelease the previously acquired mutex
ErrorsEINVAL,EPERM

Once-only execution

Initialize a once control variable:

pthread_once_t once = PTHREAD_ONCE_INIT;

pthread_once
Synopsisint pthread_once(pthread_once_t *once_control, void (*init_routine)(void));
Description Execute init_routine once
ErrorsNone

Condition Variable Attributes

All condition variable attributes are set in a condition variable attribute object by a function of the form:

int pthread_condattr_setname ( pthread_condattr_t *attr_t, Type t);

All condition variable attributes are received from a condition variable attribute object by a function of the form:

int pthread_condattr_getname ( const pthread_condattr_t *attr, Type *t );

Where name and Type are from the table below:
Type and nameDescription and Value(s)
int psharedDefines whether a condition variable is shared with other processes.

PTHREAD_PROCESS_SHARED,PTHREAD_PROCESS_PRIVATE

The functions are:

int pthread_condattr_getpshared(const pthread_condattr_t *attr, int *pshared);

int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared);

pthread_condattr_init
Synopsisint pthread_condattr_init(pthread_condattr_t *attr);
DescriptionInitialize a condition variable attribute object
ErrorsENOMEM

pthread_condattr_destroy
Synopsisint pthread_condattr_destroy(pthread_condattr_t *attr);
DescriptionDestroy a condition variable attribute object
ErrorsEINVAL


Condition Variable Usage

pthread_cond_init
Synopsisint pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
DescriptionInitialize a condition variable
ErrorsEAGAIN,ENOMEM,EBUSY,EINVAL

pthread_cond_destroy
Synopsisint pthread_cond_destroy(pthread_cond_t *cond);
DescriptionDestroy a condition variable
ErrorsEBUSY,EINVAL

pthread_cond_signal
Synopsisint pthread_cond_signal(pthread_cond_t *cond);
DescriptionUnblock at least one thread currently blocked in the specified condition variable
ErrorsEINVAL

pthread_cond_broadcast
Synopsisint pthread_cond_broadcast(pthread_cond_t *cond);
DescriptionUnblock all threads currently blocked on the specified condition variable
ErrorsEINVAL

pthread_cond_wait
Synopsisint pthread_cond_wait(pthread_cond_t *cond);
DescriptionBlock on the specified condition variable
ErrorsEINVAL
NotesThis function is a cancellation point

pthread_cond_timedwait
Synopsisint pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);
DescriptionBlock on the specified condition variable not longer than the specified absolute time
ErrorsETIMEDOUT,EINVAL
NotesThis function is a cancellation point


Thread Specific Data

pthread_key_create
Synopsisint pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
DescriptionCreate a thread-specific data key
ErrorsEAGAIN,ENOMEM
NotesThere is a system limit of PTHREAD_KEYS_MAX per process.

There is a system limit of PTHREAD_DESTRUCTOR_ITERATIONS calls to destructor per thread exit

.

pthread_key_delete
Synopsisint pthread_key_delete(pthread_key_t key);
DescriptionDestroy a thread-specific data key
ErrorsEINVAL

pthread_getspecific
Synopsisvoid *pthread_getspecific(pthread_key_t key);
DescriptionReturn the value bound to the given key for the calling thread
ErrorsENOMEM,EINVAL

pthread_setspecific
Synopsisint pthread_setspecific(pthread_key_t key, const void *value);
DescriptionSet the value for the given key in the calling thread
ErrorsENOMEM,EINVAL


Signal Management

pthread_sigmask
Synopsis#include <signal.h>

int pthread_sigmask(int how, const sigset_t *newmask, sigset_t *oldmask);

DescriptionExamine or change calling threads signal mask
ErrorsEINVAL
NotesThe value of how can be SIG_BLOCK,SIG_UNBLOCK,SIG_SETMASK

pthread_kill
Synopsis#include <signal.h>

pthread_kill( pthread_t thread, int signo );

DescriptionDeliver signal to indicated thread
Errors ESRCH,EINVAL


sigwait
Synopsisint sigwait( const sigset_t *set, int *sig );
DescriptionSynchronously accept a signal
ErrorsEINVAL,EINTR
NotesThis function is a cancellation point

Cancellation

pthread_setcancelstate
Synopsisint pthread_setcancelstate(int state, int *oldstate);
DescriptionSet the cancellation state for the calling thread
ErrorsEINVAL
NotesValues for state are PTHREAD_CANCEL_ENABLE,PTHREAD_CANCEL_DISABLE

pthread_setcanceltype
Synopsisint pthread_setcanceltype(int type, int *oldtype);
DescriptionSet the cancellation type for the calling thread
Errors EINVAL
NotesValues for type are PTHREAD_CANCEL_ENABLE,PTHREAD_CANCEL_ASYNCHRONOUS

pthread_cancel
Synopsisint pthread_cancel(pthread_t thread);
DescriptionCancel the specified thread
ErrorsESRCH
NotesThreads that have been cancelled terminate with a status of PTHREAD_CANCELLED

pthread_testcancel
Synopsisvoid pthread_testcancel(void);
DescriptionIntroduce a cancellation point
ErrorsNone
NotesThis function is a cancellation point


pthread_cleanup_push
Synopsisvoid pthread_cleanup_push(void (*routine)(void*), void *arg);
DescriptionPush an item onto the cancellation stack
ErrorsNone


pthread_cleanup_pop
Synopsisvoid pthread_cleanup_pop(int execute);
DescriptionPop the top item from the cancellation stack and optionally execute it
ErrorsNone
Notespush and pop operations must appear at the same lexical level. execute takes the values 0 or 1.


Concurrency

pthread_getconcurrency
Synopsisint pthread_getconcurrency(void);
DescriptionGet level of concurrency
ErrorsNone

pthread_setconcurrency
Synopsisint pthread_setconcurrency(int level);
DescriptionSet level of concurrency
ErrorsEINVAL,EAGAIN



Read-Write Locks

pthread_rwlock_init
Synopsisint pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr);
DescriptionInitialize a read-write lock object
ErrorsEAGAIN,ENOMEM,EPERM,EBUSY,EINVAL

pthread_rwlock_destory
Synopsisint pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
DescriptionDestroy a read-write lock object
ErrorsEBUSY,EINVAL

pthread_rwlock_rdlock
Synopsisint pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
DescriptionLock a read-write lock object for reading
ErrorsEINVAL,EDEADLCK,EAGAIN

pthread_rwlock_tryrdlock
Synopsisint pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
DescriptionLock a read-write lock for reading, unless there is an existing write lock or blocked writers
ErrorsEBUSY,EINVAL,EDEADLCK,,EAGAIN

pthread_rwlock_wrlock
Synopsisint pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
DescriptionLock a read-write lock object for writing, block if necessary until the lock becomes available
ErrorsEINVAL,EDEADLCK



pthread_rwlock_trywrlock
Synopsisint pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
DescriptionLock a read-write lock for writing, unless there are any existing read or write locks
ErrorsEBUSY,EINVAL,EDEADLCK

pthread_rwlock_unlock
Synopsisint pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
DescriptionUnlock a read-write lock object
ErrorsEINVAL,EPERM

pthread_rwlockattr_init
Synopsisint pthread_rwlockattr_init(pthread_rwlockattr_t *attr);
DescriptionInitialize a read-write lock attributes object
ErrorsENOMEM

pthread_rwlockattr_destroy
Synopsisint pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);
DescriptionDestroy a read-write lock attributes object
ErrorsEINVAL

pthread_rwlockattr_getpshared
Synopsisint pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *attr, int *pshared);
DescriptionGet the value of the process-shared attribute of a read-write lock attributes object
ErrrorsEINVAL

pthread_rwlockattr_setpshared
Synopsisint pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr, int pshared);
DescriptionSet the value of the process-shared attribute of a read-write lock attributes object
ErrrorsEINVAL


Atomic Input/Output

pread
Synopsisssize_t pread(int fildes, void * buf, size_t nbyte, off_t offset);
DescriptionAtomic read of data from file into buffer
ErrorsSee read()

pwrite
Synopsisssize_t pwrite(int fildes, const void * buf, size_t nbyte, off_t offset);
DescriptionAtomic write of data from buffer into file
ErrorsSee write()

Realtime Threads Feature Group

The following threads functions are only supported on UNIX systems if the Realtime Threads Feature group is supported (denoted by the symbol _XOPEN_REALTIME_THREADS in <unistd.h>).
pthread_attr_getinheritsched () pthread_attr_getschedpolicy()
pthread_attr_getscope() pthread_attr_setinheritsched()
pthread_attr_setschedpolicy() pthread_attr_setscope()
pthread_getschedparam() pthread_mutex_getprioceiling()
pthread_mutex_setprioceiling() pthread_mutexattr_getprioceiling()
pthread_mutexattr_getprotocol() pthread_mutexattr_setprioceiling()
pthread_mutexattr_setprotocol() pthread_setschedparam()


Thread-safety

The following functions are not guaranteed to be thread-safe on all UNIX systems:

asctime() basename() catgets() ctime()
dbm_clearerr() dbm_close() dbm_delete() dbm_error()
dbm_fetch() dbm_firstkey() dbm_nextkey() dbm_open()
dbm_store() dirname() drand48() ecvt()
encrypt() endgrent() endpwent() endutxent()
fcvt() gamma() gcvt() getc_unlocked()
getchar_unlocked() getdate() getenv() getgrent()
getgrgid() getgrnam() getlogin() getopt()
getpwnam() getpwent() getpwuid() getutxent()
getutxid() getutxline() getw() gmtime()
l64a() lgamma() lrand48() localtime()
mrand48() nl_langinfo() ptsname() putc_unlocked()
putchar_unlocked() putenv() pututxline() rand()
readdir() setgrent() setkey() setpwent()
setutxent() strerror() strtok() ttyname()

The functions ctermid() and tmpnam() need not be thread-safe if passed a NULL argument.

The functions in the Legacy Feature Group need not be thread-safe.

New Threads Related Functions

The following functions offer alternate functionality for implementing thread-safe code, some of these

functions are thread-safe versions of common POSIX.1 functions, some are non thread-safe fast functions to be used with the locking facilities also defined in this section.

asctime_r
Synopsis#include <time.h>

char *asctime_r (const struct tm *tm, char *buf);

DescriptionThread safe version of asctime()

ctime_r
Synopsis#include <time.h>

char *ctime_r(const time_t *clock, char *buf);

DescriptionThread safe version of ctime()

flockfile

Synopsis#include <stdio.h>

void flockfile(FILE * file);

DescriptionLock a stdio (FILE *) object

ftrylockfile

Synopsis#include <stdio.h>

int ftrylockfile(FILE * file);

DescriptionAttempt to lock a stdio (FILE *) object if available, do not block

funlockfile
Synopsis#include <stdio.h>

void funlockfile(FILE * file);

DescriptionUnlock a stdio (FILE *) object

getc_unlocked
Synopsis#include <stdio.h>

int getc_unlocked(FILE * stream);

DescriptionFast version of getc() to be used in conjunction with flockfile(), ftrylockfile() and funlockfile()


getchar_unlocked
Synopsis#include <stdio.h>

int getchar_unlocked(void);

DescriptionFast version of getchar() to be used in conjunction with flockfile(), ftrylockfile() and funlockfile()

getgrgid_r

Synopsis#include <grp.h>

int getgrgid_r(gid_t gid, struct group *grp, char *buffer, size_t bufsize, struct group **result);

DescriptionThread safe version of getgrgid()


getgrnam_r

Synopsisint getgrnam_r(const char * name, struct group * grp, char * buffer,size_t bufsize, struct group ** result);
DescriptionThread safe version of getgrnam()

getpwnam_r
Synopsisint getpwnam_r(const char * nam, struct passwd * pwd, char * buffer, size_t bufsize, struct passwd ** result);
Description Thread safe version of getpwnam()


getpwuid_r
Synopsisint getpwuid_r(uid_t uid, struct passwd * pwd, char * buffer, size_t bufsize, struct passwd ** result);
DescriptionThread safe version of getpwuid()



gmtime_r

Synopsis#include <time.h>

struct tm *gmtime_r(const time_t *clock, struct tm *result);

DescriptionThread safe version of gmtime()

localtime_r
Synopsis#include <time.h>

struct tm *localtime_r(const time_t *clock, struct tm *result);

DescriptionThread safe version of localtime()

putc_unlocked

Synopsis#include <stdio.h>

int putc_unlocked(int c, FILE * stream);

DescriptionFast version of putc() to be used in conjunction with flockfile(), ftrylockfile() and funlockfile()

putchar_unlocked

Synopsis#include <stdio.h>

int putchar_unlocked(int c);

DescriptionFast version of putchar() to be used in conjunction with flockfile(), ftrylockfile() and funlockfile()

rand_r
Synopsis#include <stdlib.h>

int rand_r(unsigned int *seed);

DescriptionThread safe version of rand()


readdir_r
Synopsisint readdir_r(DIR * dirp, struct direct * entry, struct dirent ** result);
DescriptionThread safe version of readdir()

strtok_r
Synopsis char *strtok_r(char * s, const char * sep, char ** lasts);
DescriptionThread safe version of strtok()



Read other technical papers.

Read or download the complete Single UNIX Specification from http://www.UNIX-systems.org/go/unix.

Copyright © 1997-1998 The Open Group

UNIX is a registered trademark of The Open Group.