{
  "id": "posix-threads",
  "title": "POSIX Threads",
  "lang": "en",
  "source_lang": "en",
  "summary": "POSIX Threads is the standardized programming interface for creating, managing, and synchronizing threads within a process on POSIX-compatible operating systems.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Pthreads",
    "pthreads",
    "POSIX thread API"
  ],
  "generated_at": "2026-11-06",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/posix-threads/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/posix-threads/",
      "json": "https://aiwiki.page/zh/posix-threads.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "POSIX Threads, commonly called Pthreads, is a standardized application programming interface for creating and managing threads and coordinating their access to shared resources. It forms part of POSIX, the family of standards for portable operating-system interfaces, and is used primarily through the C programming language. Pthreads specifies interface behavior rather than a particular implementation: different operating systems and libraries can provide the same API using different internal mechanisms.\n\nThe interface supports concurrent execution within a process and, where multiple processors are available, parallel execution. Its principal facilities include thread creation and termination, mutexes, condition variables, thread-specific data, cancellation, and scheduling attributes."
    },
    {
      "heading": "Standardization and scope",
      "text": "The thread interfaces were standardized in IEEE POSIX.1c-1995 and subsequently incorporated into the consolidated POSIX standard. They provided a common alternative to the incompatible threading interfaces previously available on different Unix systems.\n\nMost Pthreads declarations are supplied by the <pthread.h> header. Names generally begin with pthread_, while constants and initialization macros commonly begin with PTHREAD_.\n\nPthreads is not itself a programming language, a single library implementation, or a requirement that each thread correspond to a particular kernel object. It specifies observable behavior that an implementation must provide. Some facilities and attributes depend on the options supported by the implementation.\n\nThe broader POSIX environment also provides related synchronization facilities, such as semaphores, whose functions are not part of the pthread_* interface."
    },
    {
      "heading": "Execution model",
      "text": "A process contains resources such as an address space and open file descriptors. Threads within that process share much of this state, including global variables and dynamically allocated memory. Each thread nevertheless has its own execution context, including a program counter, registers, and call stack.\n\nThis combination makes threads useful for work that needs frequent access to common data. It also means that an invalid memory access or an unsynchronized modification can affect the entire process rather than remaining isolated to one thread.\n\nEach thread has an identifier of type pthread_t. This type is opaque: portable programs must not assume that it is an integer, a pointer, or a kernel thread number. pthread_self() obtains the calling thread’s identifier, and pthread_equal() compares two valid thread identifiers. Identifiers may be reused after a thread’s lifetime and associated resource-management obligations have ended.\n\nCreating a thread does not specify when it will run relative to the creator. Either thread may execute next, and the implementation may interleave their operations in many ways."
    },
    {
      "heading": "Thread creation and lifetime",
      "text": "Creation and attributes\n\npthread_create() creates a thread that begins executing a function with the signature:\n\nvoid *worker(void *argument);\n\nThe argument is a single pointer. Programs commonly use it to pass the address of a structure containing multiple inputs. The pointed-to object must remain valid for as long as the new thread accesses it; passing the address of a short-lived local variable can therefore be incorrect.\n\nA pthread_attr_t object can specify attributes such as stack size and detached state. Passing a null attribute pointer selects the default attributes. Scheduling-related attributes are subject to platform support and permission checks.\n\nMost Pthreads functions return zero on success and an error number on failure, rather than reporting failure solely through errno. Individual function specifications determine the exact convention.\n\nTermination, joining, and detachment\n\nA thread normally terminates by returning from its start routine or by calling pthread_exit(). Its result is represented by a void * value.\n\nA thread is normally created in the joinable state. Another thread can call pthread_join() to wait for its termination and retrieve its result. Joining also allows the implementation to reclaim resources retained for the terminated thread.\n\nA detached thread cannot be joined. Its associated resources are reclaimed automatically when it terminates. Detachment does not mean that the thread runs independently of the process: process termination ends detached threads as well.\n\nCalling exit(), or returning from the initial invocation of main(), terminates the process and its threads. Calling pthread_exit() from the initial thread instead terminates that thread while allowing other threads to continue.\n\nMinimal example\n\nThe following example creates a worker, waits for it to finish, and then reads the value it wrote:\n\n#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic void *worker(void *argument)\n{\n    int *result = argument;\n    *result = 42;\n    return NULL;\n}\n\nint main(void)\n{\n    pthread_t thread;\n    int result = 0;\n\n    int error = pthread_create(&thread, NULL, worker, &result);\n    if (error != 0) {\n        fprintf(stderr, \"pthread_create failed: %d\\n\", error);\n        return EXIT_FAILURE;\n    }\n\n    error = pthread_join(thread, NULL);\n    if (error != 0) {\n        fprintf(stderr, \"pthread_join failed: %d\\n\", error);\n        return EXIT_FAILURE;\n    }\n\n    printf(\"%d\\n\", result);\n    return EXIT_SUCCESS;\n}\n\nThe local variable remains alive until the worker has finished. The successful join provides the synchronization needed for the subsequent read.\n\nOn many Unix-like systems, a suitable compiler command is:\n\ncc -pthread example.c -o example\n\nThe exact command is toolchain-dependent. The -pthread option can affect both compilation and linking, so it is not necessarily equivalent to adding only -lpthread."
    },
    {
      "heading": "Synchronization facilities",
      "text": "Mutexes\n\nA mutex provides mutual exclusion: only one thread at a time can own a particular mutex. Programs use pthread_mutex_lock() and pthread_mutex_unlock() to protect a critical section that accesses shared state.\n\nMutexes work only when participating threads follow the same locking protocol. Protecting one access to an object while leaving conflicting accesses unprotected does not make the object safe.\n\nPthreads supports mutex attributes for different behavior. Depending on the mutex type, relocking a mutex already owned by the calling thread may block, report an error, or increase a recursion count. Programs must not assume that a default mutex detects misuse.\n\nRobust mutexes provide a special mechanism for detecting that an owner terminated while holding a lock. An acquisition can return EOWNERDEAD while granting ownership to the caller. The protected state then requires consistency recovery; robustness does not automatically repair application data.\n\nCondition variables\n\nA condition variable lets threads wait until a condition concerning shared state may have become true. It is normally used with a mutex and a predicate, such as “the queue is not empty.”\n\npthread_cond_wait() atomically releases the associated mutex and waits. Before returning successfully, it reacquires the mutex. The predicate must be checked in a loop:\n\npthread_mutex_lock(&mutex);\n\nwhile (!ready) {\n    pthread_cond_wait(&condition, &mutex);\n}\n\n/* Access the state protected by mutex. */\n\npthread_mutex_unlock(&mutex);\n\nThe loop is necessary because wakeups can be spurious and because another thread may change the state before the awakened thread reacquires the lock.\n\npthread_cond_signal() wakes at least one waiting thread if any are waiting; pthread_cond_broadcast() wakes all current waiters. Neither operation stores a notification for a future waiter. The shared predicate, rather than the notification alone, records whether work or another condition is available.\n\nOther facilities\n\nAdditional Pthreads synchronization mechanisms include:\n\n- Read–write locks, which allow multiple readers or one exclusive writer.\n- Barriers, which hold participating threads until a specified number have arrived.\n- Spin locks, which wait by repeatedly attempting to acquire a lock rather than using a blocking wait.\n- One-time initialization, through pthread_once(), which coordinates a single execution of an initialization routine.\n\nAvailability and performance characteristics vary by platform and supported POSIX options."
    },
    {
      "heading": "Memory visibility and data races",
      "text": "Synchronization governs both execution order and the visibility of memory operations. Merely assuming that one thread “must have finished by now” does not establish a valid ordering.\n\nAn unlock followed by a successful acquisition of the same mutex provides synchronization between the participating threads. Thread creation and successful joining also establish specified memory-ordering relationships. These guarantees interact with the language’s memory model.\n\nIn C, conflicting accesses to the same memory location, with at least one write, can constitute a data race if they lack the required synchronization and are not appropriately atomic. Such races produce undefined behavior. A race condition is a broader concept: even code without a language-level data race can produce incorrect results because of an unintended ordering of operations.\n\nDeclaring a variable volatile does not make it safe for inter-thread communication. Language-level atomic operations can support particular communication patterns without a mutex, but they require appropriate memory ordering and do not automatically preserve invariants spanning several objects."
    },
    {
      "heading": "Thread-specific data and cancellation",
      "text": "Thread-specific data\n\nPthreads provides thread-specific data through keys created with pthread_key_create(). Each thread can associate its own pointer value with the same key using pthread_setspecific() and retrieve it using pthread_getspecific().\n\nA key can have a destructor that is invoked for applicable non-null values during thread termination. This facility supports per-thread library state without requiring every function to receive an explicit context argument. It is distinct from language-level thread-local storage, although both can serve related purposes.\n\nCancellation\n\npthread_cancel() requests cancellation of another thread. It does not necessarily stop the target immediately.\n\nCancellation behavior depends on the target’s cancellation state and type. The usual default is enabled, deferred cancellation: a request takes effect when the thread reaches a cancellation point. Asynchronous cancellation permits cancellation at far less predictable points and is difficult to reconcile with resource invariants.\n\nCleanup handlers registered through pthread_cleanup_push() and pthread_cleanup_pop() can release resources during cancellation or an explicit pthread_exit(). Cancellation therefore requires a deliberate resource-management protocol; it is not a general-purpose substitute for cooperative shutdown."
    },
    {
      "heading": "Scheduling, signals, and process creation",
      "text": "Pthreads exposes scheduling policies, priorities, and related attributes. Their effects depend on the operating system, privileges, and supported scheduling facilities. The API does not promise a particular execution order, equal progress among threads, or faster execution simply because more threads exist.\n\nSignals have both process-wide and thread-specific aspects. Signal dispositions are shared across a process, while each thread has its own signal mask. pthread_sigmask() changes the calling thread’s mask, and pthread_kill() directs a signal to a specified thread. A signal whose default action terminates the process still terminates the process even when directed to one thread.\n\nCalling fork() from a multithreaded process introduces special constraints. In the child, only the calling thread survives, while memory may contain locks previously held by other threads. POSIX therefore restricts the operations the child can perform before executing a new program. pthread_atfork() provides handlers around fork(), but it does not remove the general difficulty of coordinating locks across independently developed libraries."
    },
    {
      "heading": "Implementations, uses, and limitations",
      "text": "On Linux, the Native POSIX Thread Library, or NPTL, implements Pthreads using a one-to-one mapping between POSIX threads and kernel-scheduled threads. Other historical implementations used different mappings. The standardized interface does not require a particular mapping or an identical binary interface across systems.\n\nPthreads is widely used in servers, runtime libraries, scientific software, and applications that perform blocking input/output alongside computation. Higher-level threading systems can use it internally. By contrast, OpenMP primarily expresses parallel work through language directives and a runtime, while the Message Passing Interface primarily provides communication among processes.\n\nIts portability is principally source-level. Extensions such as thread affinity controls and thread naming are common but are not uniformly portable. Pthreads is also not the native threading interface of Microsoft Windows, although compatibility implementations exist.\n\nThe interface exposes relatively low-level mechanisms, leaving applications responsible for task decomposition, shared-state ownership, shutdown, and lock ordering. Incorrect coordination can produce deadlocks, starvation, missed state transitions, or memory-lifetime errors. Excessive thread counts can increase scheduling and memory costs, while lock contention can serialize work. Consequently, using Pthreads enables concurrency but does not by itself guarantee correctness, scalability, or improved performance."
    }
  ],
  "links": [
    "application-programming-interface",
    "thread-computing",
    "posix",
    "c-programming-language",
    "concurrent-computing",
    "parallel-computing",
    "unix",
    "semaphore-computing",
    "process-computing",
    "call-stack",
    "mutex",
    "mutual-exclusion",
    "critical-section",
    "condition-variable",
    "spinlock",
    "memory-model",
    "race-condition",
    "atomic-operation",
    "operating-system",
    "linux",
    "openmp",
    "message-passing-interface",
    "microsoft-windows",
    "deadlock"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}