# info > pthreads

---
type: CommandReference
command: pthreads
mode: man
section: 7
source: man-pages
---

## Quick Reference

- `cc -pthread` — compile programs using POSIX threads
- `getconf GNU_LIBPTHREAD_VERSION` — display threading implementation version
- `LD_ASSUME_KERNEL=<version>` — override threading library selection (e.g., `LD_ASSUME_KERNEL=2.2.5` for LinuxThreads)
- `pthread_create()` — create a new thread
- `pthread_join()` — wait for a thread to terminate
- `pthread_self()` — obtain own thread identifier
- `pthread_mutex_lock()` — lock a mutex
- `pthread_mutex_unlock()` — unlock a mutex

## Name

pthreads - POSIX threads

## Synopsis

Link with `cc -pthread` when compiling programs that use the Pthreads API.

## Description

POSIX.1 specifies a set of interfaces (functions, header files) for threaded programming known as POSIX threads (Pthreads). A single process can contain multiple threads executing the same program, sharing global memory (data and heap segments) but each having its own stack.

### Shared attributes (process-wide)

- Process ID, parent process ID, process group ID, session ID
- Controlling terminal, user and group IDs
- Open file descriptors, record locks ([fcntl(2)](https://www.kernel.org/doc/man-pages/man2/fcntl.2.html))
- Signal dispositions, file mode creation mask ([umask(2)](https://www.kernel.org/doc/man-pages/man2/umask.2.html))
- Current directory ([chdir(2)](https://www.kernel.org/doc/man-pages/man2/chdir.2.html)), root directory ([chroot(2)](https://www.kernel.org/doc/man-pages/man2/chroot.2.html))
- Interval timers ([setitimer(2)](https://www.kernel.org/doc/man-pages/man2/setitimer.2.html)), POSIX timers ([timer_create(2)](https://www.kernel.org/doc/man-pages/man2/timer_create.2.html))
- Nice value ([setpriority(2)](https://www.kernel.org/doc/man-pages/man2/setpriority.2.html)), resource limits ([setrlimit(2)](https://www.kernel.org/doc/man-pages/man2/setrlimit.2.html))
- CPU time consumption ([times(2)](https://www.kernel.org/doc/man-pages/man2/times.2.html), [getrusage(2)](https://www.kernel.org/doc/man-pages/man2/getrusage.2.html))

### Per-thread attributes

- Thread ID (`pthread_t`)
- Signal mask ([pthread_sigmask(3)](https://www.kernel.org/doc/man-pages/man3/pthread_sigmask.3.html))
- `errno` variable
- Alternate signal stack ([sigaltstack(2)](https://www.kernel.org/doc/man-pages/man2/sigaltstack.2.html))
- Real-time scheduling policy and priority ([sched(7)](https://www.kernel.org/doc/man-pages/man7/sched.7.html))
- Linux-specific: capabilities ([capabilities(7)](https://www.kernel.org/doc/man-pages/man7/capabilities.7.html)), CPU affinity ([sched_setaffinity(2)](https://www.kernel.org/doc/man-pages/man2/sched_setaffinity.2.html))

### Pthreads function return values

Most pthreads functions return 0 on success, an error number on failure. They do not set `errno`. POSIX.1 specifies that the functions can never fail with `EINTR`.

### Thread IDs

Each thread has a unique identifier (`pthread_t`). Returned by `pthread_create()`, obtained via `pthread_self()`. IDs are unique only within a process and may be reused after a thread is joined or detached.

### Thread-safe functions

A thread-safe function can be safely called from multiple threads simultaneously. All functions specified in the standard shall be thread-safe except the following:

text
asctime, basename, catgets, crypt, ctermid (if non-NULL), ctime, dbm_clearerr, dbm_close, dbm_delete, dbm_error, dbm_fetch, dbm_firstkey, dbm_nextkey, dbm_open, dbm_store, dirname, dlerror, drand48, ecvt, encrypt, endgrent, endpwent, endutxent, fcvt, ftw, gcvt, getc_unlocked, getchar_unlocked, getdate, getenv, getgrent, getgrgid, getgrnam, gethostbyaddr, gethostbyname, gethostent, getlogin, getnetbyaddr, getnetbyname, getnetent, getopt, getprotobyname, getprotobynumber, getprotoent, getpwent, getpwnam, getpwuid, getservbyname, getservbyport, getservent, getutxent, getutxid, getutxline, gmtime, hcreate, hdestroy, hsearch, inet_ntoa, l64a, lgamma, lgammaf, lgammal, localeconv, localtime, lrand48, mrand48, nftw, nl_langinfo, ptsname, putc_unlocked, putchar_unlocked, putenv, pututxline, rand, readdir, setenv, setgrent, setkey, setpwent, setutxent, strerror, strsignal, strtok, system, tmpnam (if non-NULL), ttyname, unsetenv, wcrtomb (if final arg NULL), wcsrtombs (if final arg NULL), wcstombs, wctomb
Note: `ecvt`, `fcvt`, `gcvt`, `gethostbyaddr`, `gethostbyname` are POSIX.1-2001 only (removed in POSIX.1-2008). `strsignal` and `system` added in POSIX.1-2008.

### Async-cancel-safe functions

Only the following functions are required to be async-cancel-safe:

- `pthread_cancel()`
- `pthread_setcancelstate()`
- `pthread_setcanceltype()`

### Cancellation points

Functions that are required to be cancellation points (POSIX.1-2001/2008):

text
accept, aio_suspend, clock_nanosleep, close, connect, creat, fcntl (F_SETLKW), fdatasync, fsync, getmsg, getpmsg, lockf (F_LOCK), mq_receive, mq_send, mq_timedreceive, mq_timedsend, msgrcv, msgsnd, msync, nanosleep, open, openat, pause, poll, pread, pselect, pthread_cond_timedwait, pthread_cond_wait, pthread_join, pthread_testcancel, putmsg, putpmsg, pwrite, read, readv, recv, recvfrom, recvmsg, select, sem_timedwait, sem_wait, send, sendmsg, sendto, sigpause, sigsuspend, sigtimedwait, sigwait, sigwaitinfo, sleep, system, tcdrain, usleep, wait, waitid, waitpid, write, writev
Functions that may be cancellation points (POSIX.1-2001/2008):

text
access, asctime, asctime_r, catclose, catgets, catopen, chmod, chown, closedir, closelog, ctermid, ctime, ctime_r, dbm_close, dbm_delete, dbm_fetch, dbm_nextkey, dbm_open, dbm_store, dlclose, dlopen, dprintf, endgrent, endhostent, endnetent, endprotoent, endpwent, endservent, endutxent, faccessat, fchmod, fchmodat, fchown, fchownat, fclose, fcntl (any value), fflush, fgetc, fgetpos, fgets, fgetwc, fgetws, fmtmsg, fopen, fpathconf, fprintf, fputc, fputs, fputwc, fputws, fread, freopen, fscanf, fseek, fseeko, fsetpos, fstat, fstatat, ftell, ftello, ftw, futimens, fwprintf, fwrite, fwscanf, getaddrinfo, getc, getc_unlocked, getchar, getchar_unlocked, getcwd, getdate, getdelim, getgrent, getgrgid, getgrgid_r, getgrnam, getgrnam_r, gethostbyaddr, gethostbyname, gethostent, gethostid, gethostname, getline, getlogin, getlogin_r, getnameinfo, getnetbyaddr, getnetbyname, getnetent, getopt (if opterr nonzero), getprotobyname, getprotobynumber, getprotoent, getpwent, getpwnam, getpwnam_r, getpwuid, getpwuid_r, gets, getservbyname, getservbyport, getservent, getutxent, getutxid, getutxline, getwc, getwchar, getwd, glob, iconv_close, iconv_open, ioctl, link, linkat, lio_listio, localtime, localtime_r, lockf, lseek, lstat, mkdir, mkdirat, mkdtemp, mkfifo, mkfifoat, mknod, mknodat, mkstemp, mktime, nftw, opendir, openlog, pathconf, pclose, perror, popen, posix_fadvise, posix_fallocate, posix_madvise, posix_openpt, posix_spawn, posix_spawnp, posix_trace_clear, posix_trace_close, posix_trace_create, posix_trace_create_withlog, posix_trace_eventtypelist_getnext_id, posix_trace_eventtypelist_rewind, posix_trace_flush, posix_trace_get_attr, posix_trace_get_filter, posix_trace_get_status, posix_trace_getnext_event, posix_trace_open, posix_trace_rewind, posix_trace_set_filter, posix_trace_shutdown, posix_trace_timedgetnext_event, posix_typed_mem_open, printf, psiginfo, psignal, pthread_rwlock_rdlock, pthread_rwlock_timedrdlock, pthread_rwlock_timedwrlock, pthread_rwlock_wrlock, putc, putc_unlocked, putchar, putchar_unlocked, puts, pututxline, putwc, putwchar, readdir, readdir_r, readlink, readlinkat, remove, rename, renameat, rewind, rewinddir, scandir, scanf, seekdir, semop, setgrent, sethostent, setnetent, setprotoent, setpwent, setservent, setutxent, sigpause, stat, strerror, strerror_r, strftime, symlink, symlinkat, sync, syslog, tmpfile, tmpnam, ttyname, ttyname_r, tzset, ungetc, ungetwc, unlink, unlinkat, utime, utimensat, utimes, vdprintf, vfprintf, vfwprintf, vprintf, vwprintf, wcsftime, wordexp, wprintf, wscanf
Note: Even without asynchronous cancellation, calling a function from the cancellation point list in an asynchronous signal handler may cause equivalent asynchronous cancellation.

### Compiling on Linux

Use `cc -pthread`.

### Linux implementations

Two threading implementations have been provided by glibc:

- **LinuxThreads**: Original implementation, no longer supported since glibc 2.4. Creates a "manager" thread. Uses first three real-time signals (or SIGUSR1/SIGUSR2 on older kernels). Threads do not share process IDs. Many nonconformances (see below).
- **NPTL (Native POSIX Threads Library)**: Modern implementation, available since glibc 2.3.2, requires Linux 2.6 kernel. All threads in same thread group; no manager thread. Uses first two real-time signals internally. Closer POSIX conformance.

Both are 1:1 implementations (each thread maps to a kernel scheduling entity). Thread synchronization primitives in NPTL use [futex(2)](https://www.kernel.org/doc/man-pages/man2/futex.2.html).

#### LinuxThreads nonconformances

- `getpid()` returns different value in each thread.
- `getppid()` in non-main threads returns manager thread ID.
- Only the creating thread can `wait()` on a child process.
- After `execve()`, resulting process has PID of the calling thread, not the main thread.
- Threads do not share user/group IDs, session ID, process group ID, record locks, semaphore undo values, interval timers, nice value, resource limits (CPU time per-thread).
- No support for process-directed signals; signals can only be sent to specific threads.
- Alternate signal stack settings are copied from creator thread; threads may share stack.

#### NPTL nonconformances

- Threads do not share a common nice value.
- Older kernel issues:
  - `times()` and `getrusage()` per-thread (fixed in 2.6.9)
  - Resource limits not shared (fixed in 2.6.10)
  - Interval timers not shared (fixed in 2.6.12)
  - Only main thread can create session or process group leader (fixed in 2.6.16)
  - Alternate signal stack settings copied from creator (fixed in 2.6.16)

If `RLIMIT_STACK` is set to a value other than unlimited, it defines the default stack size for new threads.

### Determining the threading implementation

shell
getconf GNU_LIBPTHREAD_VERSION
# Example output: NPTL 2.3.4
With older glibc:

shell
$( ldd /bin/ls | grep libc.so | awk '{print $3}' ) | egrep -i 'threads|nptl'
### Selecting the threading implementation: LD_ASSUME_KERNEL

Set `LD_ASSUME_KERNEL` environment variable to override dynamic linker's choice. For example, to force LinuxThreads:

shell
LD_ASSUME_KERNEL=2.2.5 ldd /bin/ls | grep libc.so | awk '{print $3}' | egrep -i 'threads|nptl'
## Options

### Thread Management

- `pthread_create()` — create a new thread
- `pthread_join()` — wait for a thread to terminate
- `pthread_detach()` — detach a thread
- `pthread_exit()` — terminate calling thread
- `pthread_cancel()` — send a cancellation request to a thread
- `pthread_self()` — obtain own thread identifier
- `pthread_equal()` — compare thread IDs
- `pthread_once()` — call a function once

### Mutexes

- `pthread_mutex_lock()` — lock a mutex (blocking)
- `pthread_mutex_trylock()` — attempt to lock a mutex without blocking
- `pthread_mutex_unlock()` — unlock a mutex
- `pthread_mutex_init()` — initialize a mutex
- `pthread_mutex_destroy()` — destroy a mutex

### Condition Variables

- `pthread_cond_wait()` — wait on a condition variable
- `pthread_cond_timedwait()` — wait on a condition variable with timeout
- `pthread_cond_signal()` — signal one thread waiting on a condition
- `pthread_cond_broadcast()` — signal all threads waiting on a condition

### Read-Write Locks

- `pthread_rwlock_rdlock()` — acquire read lock (blocking)
- `pthread_rwlock_tryrdlock()` — attempt to acquire read lock
- `pthread_rwlock_wrlock()` — acquire write lock (blocking)
- `pthread_rwlock_trywrlock()` — attempt to acquire write lock
- `pthread_rwlock_unlock()` — release read-write lock

### Spin Locks

- `pthread_spin_lock()` — lock a spin lock
- `pthread_spin_trylock()` — attempt to lock a spin lock
- `pthread_spin_unlock()` — unlock a spin lock
- `pthread_spin_init()` — initialize a spin lock
- `pthread_spin_destroy()` — destroy a spin lock

### Thread-Specific Data

- `pthread_key_create()` — create a thread-specific data key
- `pthread_key_delete()` — delete a thread-specific data key
- `pthread_setspecific()` — set thread-specific data
- `pthread_getspecific()` — get thread-specific data

### Signals

- `pthread_sigmask()` — examine or change signal mask
- `pthread_kill()` — send a signal to a thread
- `pthread_sigqueue()` — send a signal with data to a thread

### Cancellation

- `pthread_setcancelstate()` — set cancelability state (`PTHREAD_CANCEL_ENABLE` or `PTHREAD_CANCEL_DISABLE`)
- `pthread_setcanceltype()` — set cancelability type (`PTHREAD_CANCEL_DEFERRED` or `PTHREAD_CANCEL_ASYNCHRONOUS`)
- `pthread_testcancel()` — create a cancellation point

### Thread Attributes

- `pthread_attr_init()` — initialize thread attributes object
- `pthread_attr_destroy()` — destroy thread attributes object
- `pthread_attr_setdetachstate()` — set detach state attribute
- `pthread_attr_getdetachstate()` — get detach state attribute
- `pthread_attr_setstacksize()` — set stack size attribute
- `pthread_attr_getstacksize()` — get stack size attribute
- `pthread_attr_setstackaddr()` — set stack address attribute (deprecated)
- `pthread_attr_getstackaddr()` — get stack address attribute (deprecated)

### Other

- `pthread_cleanup_push()` — push a cleanup handler
- `pthread_cleanup_pop()` — pop a cleanup handler
- `pthread_atfork()` — prepare for fork handling
- `pthread_condattr_init()` — initialize condition variable attributes
- `pthread_condattr_destroy()` — destroy condition variable attributes
- `pthread_mutexattr_init()` — initialize mutex attributes
- `pthread_mutexattr_destroy()` — destroy mutex attributes
- `pthread_rwlockattr_init()` — initialize read-write lock attributes
- `pthread_rwlockattr_destroy()` — destroy read-write lock attributes

## Examples

shell
# Compile a program with POSIX threads
cc -pthread prog.c -o prog

# Check the threading implementation version
getconf GNU_LIBPTHREAD_VERSION

# Override threading library (force LinuxThreads)
LD_ASSUME_KERNEL=2.2.5 ./program
## See Also

- [clone(2)](https://www.kernel.org/doc/man-pages/man2/clone.2.html)
- [fork(2)](https://www.kernel.org/doc/man-pages/man2/fork.2.html)
- [futex(2)](https://www.kernel.org/doc/man-pages/man2/futex.2.html)
- [gettid(2)](https://www.kernel.org/doc/man-pages/man2/gettid.2.html)
- [proc(5)](https://www.kernel.org/doc/man-pages/man5/proc.5.html)
- [attributes(7)](https://www.kernel.org/doc/man-pages/man7/attributes.7.html)
- [futex(7)](https://www.kernel.org/doc/man-pages/man7/futex.7.html)
- [nptl(7)](https://www.kernel.org/doc/man-pages/man7/nptl.7.html)
- [sigevent(7)](https://www.kernel.org/doc/man-pages/man7/sigevent.7.html)
- [signal(7)](https://www.kernel.org/doc/man-pages/man7/signal.7.html)
- Various pthreads manual pages: [pthread_create(3)](https://www.kernel.org/doc/man-pages/man3/pthread_create.3.html), [pthread_join(3)](https://www.kernel.org/doc/man-pages/man3/pthread_join.3.html), [pthread_mutex_lock(3)](https://www.kernel.org/doc/man-pages/man3/pthread_mutex_lock.3.html), and many others.