# Pthreads

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Pthreads
> Markdown URL: https://mediated.wiki/source/Pthreads.md
> Source: https://en.wikipedia.org/wiki/Pthreads
> Source revision: 1342501295
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{short description|Execution model which allows for parallel computing}}{{lowercase}}
In [computing](/source/computing), '''POSIX Threads''', commonly known as '''pthreads''' (after its header '''{{mono|<pthread.h>}}'''), is an [execution model](/source/execution_model) that exists independently from a [programming language](/source/programming_language), as well as a [parallel execution](/source/Parallel_computing) model.  It allows a [program](/source/Computer_program) to control multiple different flows of work that overlap in time.  Each flow of work is referred to as a ''[thread](/source/thread_(computing))'', and creation and control over these flows is achieved by making calls to the POSIX Threads [API](/source/API). POSIX Threads is an API defined by the [Institute of Electrical and Electronics Engineers](/source/Institute_of_Electrical_and_Electronics_Engineers) (IEEE) standard ''[POSIX](/source/POSIX).1c, Threads extensions (IEEE Std 1003.1c-1995)''.

Implementations of the API are available on many [Unix-like](/source/Unix-like) POSIX-conformant [operating system](/source/operating_system)s such as [FreeBSD](/source/FreeBSD), [NetBSD](/source/NetBSD), [OpenBSD](/source/OpenBSD), [Linux](/source/Linux), [macOS](/source/macOS), [Android](/source/Android_(operating_system)),<ref>{{cite web|url=https://android.googlesource.com/platform/bionic/+/10ce969/libc/bionic/pthread.c|title=libc/bionic/pthread.c - platform/bionic - Git at Google|website=android.googlesource.com}}</ref> [Solaris](/source/Solaris_(operating_system)), [Redox](/source/Redox_(operating_system)), [QNX](/source/QNX), and [AUTOSAR](/source/AUTOSAR) Adaptive, typically bundled as a library '''libpthread'''. [DR-DOS](/source/DR-DOS) and [Microsoft Windows](/source/Microsoft_Windows) implementations also exist: within the [SFU/SUA](/source/Windows_Services_for_UNIX) subsystem which provides a native implementation of a number of POSIX APIs, and also within [third-party](/source/third-party_software_component) packages such as ''pthreads-w32'',<ref>{{cite web|url=http://sources.redhat.com/pthreads-win32/conformance.html|title=Pthread Win-32: Level of standards conformance|date=2006-12-22|access-date=2010-08-29|archive-date=2010-06-11|archive-url=https://web.archive.org/web/20100611172430/http://sources.redhat.com/pthreads-win32/conformance.html|url-status=dead}}</ref> which implements pthreads on top of existing [Windows API](/source/Windows_API).

==Contents==
pthreads defines a set of [C](/source/C_(programming_language)) programming language [types](/source/data_type), [functions](/source/function_(computer_science)) and constants. It is implemented with a <code>pthread.h</code> header and a thread [library](/source/Library_(computing)).

There are around 100 threads procedures, all prefixed <code>pthread_</code> and they can be categorized into five groups:

*Thread management – creating, joining threads etc.
*[Mutex](/source/Mutex)es
*[Condition variable](/source/Condition_variable)s
*[Synchronization](/source/synchronization_(computer_science)) between threads using [read write locks](/source/Readers%E2%80%93writer_lock) and [barriers](/source/Barrier_(computer_science))
*[Spinlock](/source/Spinlock)s<ref>{{cite web |title=pthread.h(0p) — Linux manual page |url=https://www.man7.org/linux/man-pages/man0/pthread.h.0p.html |access-date=18 December 2022}}</ref>

The POSIX [semaphore](/source/semaphore_(programming)) API works with POSIX threads but is not part of the threads standard, having been defined in the ''POSIX.1b, Real-time extensions (IEEE Std 1003.1b-1993)'' standard. Consequently, the semaphore procedures are prefixed by <code>sem_</code> instead of <code>pthread_</code>.

==Example==
An example illustrating the use of pthreads in C:

<syntaxhighlight lang="c">
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 5

void* perform_work(void* arguments){
    int index = *((int*)arguments);
    int sleep_time = 1 + rand() % NUM_THREADS;
    printf("Thread %d: Started.\n", index);
    printf("Thread %d: Will be sleeping for %d seconds.\n", index, sleep_time);
    sleep(sleep_time);
    printf("Thread %d: Ended.\n", index);
    return NULL;
}

int main(void) {
    pthread_t threads[NUM_THREADS];
    int thread_args[NUM_THREADS];
    int result_code;
  
    //create all threads one by one
    for (int i = 0; i < NUM_THREADS; i++) {
        printf("In main: Creating thread %d.\n", i);
        thread_args[i] = i;
        result_code = pthread_create(&threads[i], NULL, perform_work, &thread_args[i]);
        assert(!result_code);
    }

    printf("In main: All threads are created.\n");

    // wait for each thread to complete
    for (int i = 0; i < NUM_THREADS; i++) {
        result_code = pthread_join(threads[i], NULL);
        assert(!result_code);
        printf("In main: Thread %d has ended.\n", i);
    }

    printf("Main program has ended.\n");
    return 0;
}

</syntaxhighlight>

This program creates five threads, each executing the function ''perform_work'' that prints the unique number of this thread to standard output.  If a programmer wanted the threads to communicate with each other, this would require defining a variable outside of the scope of any of the functions, making it a [global variable](/source/global_variable). This program can be compiled using the [gcc](/source/GNU_Compiler_Collection) compiler with the following command:
 gcc pthreads_demo.c -pthread -o pthreads_demo
Here is one of the many possible outputs from running this program.
<syntaxhighlight lang="output">
In main: Creating thread 0.
In main: Creating thread 1.
In main: Creating thread 2.
In main: Creating thread 3.
Thread 0: Started.
In main: Creating thread 4.
Thread 3: Started.
Thread 2: Started.
Thread 0: Will be sleeping for 3 seconds.
Thread 1: Started.
Thread 1: Will be sleeping for 5 seconds.
Thread 2: Will be sleeping for 4 seconds.
Thread 4: Started.
Thread 4: Will be sleeping for 1 seconds.
In main: All threads are created.
Thread 3: Will be sleeping for 4 seconds.
Thread 4: Ended.
Thread 0: Ended.
In main: Thread 0 has ended.
Thread 2: Ended.
Thread 3: Ended.
Thread 1: Ended.
In main: Thread 1 has ended.
In main: Thread 2 has ended.
In main: Thread 3 has ended.
In main: Thread 4 has ended.
Main program has ended.
</syntaxhighlight>

== POSIX Threads for Windows ==
Windows does not support the pthreads standard natively; therefore, the Pthreads4w project seeks to provide a portable and open-source [wrapper](/source/Wrapper_library) implementation. It can also be used to port [Unix](/source/Unix) software (which uses pthreads) with little or no modification to the Windows platform.<ref>{{cite web |url=http://world.std.com/~jmhart/opensource.htm |title=Experiments with the Open Source Pthreads Library and Some Comments |last=Hart |first=Johnson M. |date=2004-11-21 |access-date=2010-08-29 |url-status=dead |archive-url=https://web.archive.org/web/20100830235615/http://world.std.com/~jmhart/opensource.htm |archive-date=2010-08-30 }}</ref> Pthreads4w version 3.0.0<ref>[https://sourceforge.net/projects/pthreads4w/files/ File: pthreads4w-code-v3.0.0.zip – Source for pthreads4w v3.0.0]</ref> or later, released under the Apache Public License v2.0, is compatible with 64-bit or 32-bit Windows systems. Version 2.11.0,<ref>[https://sourceforge.net/projects/pthreads4w/files/ File: pthreads4w-code-v2.11.0.zip – Source for pthreads4w v2.11.0]</ref> released under the LGPLv3 license, is also 64-bit or 32-bit compatible.

The [Mingw-w64](/source/Mingw-w64) project also contains a wrapper implementation of 'pthreads, '''winpthreads''', which tries to use more native system calls than the Pthreads4w project.<ref>see http://locklessinc.com/articles/pthreads_on_windows which is where it was originally derived from</ref>

[Interix](/source/Interix) environment subsystem available in the [Windows Services for UNIX/Subsystem for UNIX-based Applications](/source/Windows_Services_for_UNIX) package provides a native port of the pthreads API, i.e. not mapped on Win32 API but built directly on the operating system [syscall](/source/syscall) interface.<ref>{{cite web |url=https://technet.microsoft.com/en-us/library/bb496994.aspx |title=Chapter 1: Introduction to Windows Services for UNIX 3.5|date=5 December 2007 }}</ref>

==See also==
* [Runtime system](/source/Runtime_system)
* [OpenMP](/source/OpenMP)
* [Cilk](/source/Cilk)/[Cilk Plus](/source/Cilk_Plus)
* [Threading Building Blocks](/source/Threading_Building_Blocks) (TBB)
* [Native POSIX Thread Library](/source/Native_POSIX_Thread_Library) (NPTL)
* [DCEThreads](/source/DCEThreads)
* [clone (Linux system call)](/source/clone_(Linux_system_call))
* [Spurious wakeup](/source/Spurious_wakeup)
* [Thread-local storage](/source/Thread-local_storage)
* [GNU Portable Threads](/source/GNU_Portable_Threads)
* [Grand Central Dispatch](/source/Grand_Central_Dispatch) (Apple's thread library)
* [State Threads](/source/State_Threads), an event driven approach to threading

==References==
{{reflist|2}}

==Further reading==
*{{cite book |author=David R. Butenhof|title =Programming with POSIX Threads| publisher= Addison-Wesley | isbn= 978-0-201-63392-4|year =1997}}
*{{cite book |author1=Bradford Nichols |author2=Dick Buttlar |author3=Jacqueline Proulx Farell |title=Pthreads Programming |publisher=O'Reilly & Associates |isbn=978-1-56592-115-3 |date=September 1996 |url-access=registration |url=https://archive.org/details/pthreadsprogramm00nich }}
*{{cite book | author= Charles J. Northrup | title= Programming with UNIX Threads | publisher= John Wiley & Sons | isbn= 978-0-471-13751-1 | date= 1996-01-25 | url-access= registration | url= https://archive.org/details/programmingwithu0000nort }}
*{{cite book  |author1=Kay A. Robbins  |author2=Steven Robbins  |name-list-style=amp  |title=UNIX Systems Programming  |publisher=Prentice-Hall  |isbn=978-0-13-042411-2  |year=2003  |url-access=registration  |url=https://archive.org/details/unixsystemsprogr0000robb  }}

== External links ==
* [http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/pthread.h.html The Open Group Base Specifications Issue 7, IEEE Std 1003.1]
{{Parallel Computing}}

{{DEFAULTSORT:Posix Threads}}
Category:C POSIX library
Category:Parallel computing
Category:Threads (computing)

---
Adapted from the Wikipedia article [Pthreads](https://en.wikipedia.org/wiki/Pthreads) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Pthreads?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
