Pthreads

Last updated

In computing, POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a programming language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time. Each flow of work is referred to as a thread , and creation and control over these flows is achieved by making calls to the POSIX Threads API. POSIX Threads is an API defined by the Institute of Electrical and Electronics Engineers (IEEE) standard POSIX.1c, Threads extensions (IEEE Std 1003.1c-1995).

Contents

Implementations of the API are available on many Unix-like POSIX-conformant operating systems such as FreeBSD, NetBSD, OpenBSD, Linux, macOS, Android, [1] Solaris, Redox, and AUTOSAR Adaptive, typically bundled as a library libpthread. DR-DOS and Microsoft Windows implementations also exist: within the SFU/SUA subsystem which provides a native implementation of a number of POSIX APIs, and also within third-party packages such as pthreads-w32, [2] which implements pthreads on top of existing Windows API.

Contents

pthreads defines a set of C programming language types, functions and constants. It is implemented with a pthread.h header and a thread library.

There are around 100 threads procedures, all prefixed pthread_ and they can be categorized into four groups:

The POSIX semaphore 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 sem_ instead of pthread_.

Example

An example illustrating the use of pthreads in C:

#include<stdio.h>#include<stdlib.h>#include<assert.h>#include<pthread.h>#include<unistd.h>#define NUM_THREADS 5void*perform_work(void*arguments){intindex=*((int*)arguments);intsleep_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);returnNULL;}intmain(void){pthread_tthreads[NUM_THREADS];intthread_args[NUM_THREADS];inti;intresult_code;//create all threads one by onefor(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 completefor(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");return0;}

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. This program can be compiled using the gcc 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.

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.

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 implementation. It can also be used to port Unix software (which uses pthreads) with little or no modification to the Windows platform. [4] Pthreads4w version 3.0.0 [5] or later, released under the Apache Public License v2.0, is compatible with 64-bit or 32-bit Windows systems. Version 2.11.0, [6] released under the LGPLv3 license, is also 64-bit or 32-bit compatible.

The Mingw-w64 project also contains a wrapper implementation of 'pthreads, winpthreads, which tries to use more native system calls than the Pthreads4w project. [7]

Interix environment subsystem available in the Windows Services for UNIX/Subsystem for UNIX-based Applications package provides a native port of the pthreads API, i.e. not mapped on Win32 API but built directly on the operating system syscall interface. [8]

See also

Related Research Articles

The Portable Operating System Interface is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system and user-level application programming interfaces (APIs), along with command line shells and utility interfaces, for software compatibility (portability) with variants of Unix and other operating systems. POSIX is also a trademark of the IEEE. POSIX is intended to be used by both application and system developers.

<span class="mw-page-title-main">Thread (computing)</span> Smallest sequence of programmed instructions that can be managed independently by a scheduler

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system. In many cases, a thread is a component of a process.

Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain sockets, used for inter-process communication (IPC). It is commonly implemented as a library of linkable modules. It originated with the 4.2BSD Unix operating system, which was released in 1983.

In computing, particularly in the context of the Unix operating system and its workalikes, fork is an operation whereby a process creates a copy of itself. It is an interface which is required for compliance with the POSIX and Single UNIX Specification standards. It is usually implemented as a C standard library wrapper to the fork, clone, or other system calls of the kernel. Fork is the primary method of process creation on Unix-like operating systems.

The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it. Since ANSI C was adopted by the International Organization for Standardization, the C standard library is also called the ISO C library.

RTLinux is a hard realtime real-time operating system (RTOS) microkernel that runs the entire Linux operating system as a fully preemptive process. The hard real-time property makes it possible to control robots, data acquisition systems, manufacturing plants, and other time-sensitive instruments and machines from RTLinux applications. The design was patented. Despite the similar name, it is not related to the Real-Time Linux project of the Linux Foundation.

In computing, mmap(2) is a POSIX-compliant Unix system call that maps files or devices into memory. It is a method of memory-mapped file I/O. It implements demand paging because file contents are not immediately read from disk and initially use no physical RAM at all. The actual reads from disk are performed after a specific location is accessed, in a lazy manner. After the mapping is no longer needed, the pointers must be unmapped with munmap(2). Protection information—for example, marking mapped regions as executable—can be managed using mprotect(2), and special treatment can be enforced using madvise(2).

In computer science and software engineering, busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available. Spinning can also be used to generate an arbitrary time delay, a technique that was necessary on systems that lacked a method of waiting a specific length of time. Processor speeds vary greatly from computer to computer, especially as some processors are designed to dynamically adjust speed based on current workload. Consequently, spinning as a time-delay technique can produce unpredictable or even inconsistent results on different systems unless code is included to determine the time a processor takes to execute a "do nothing" loop, or the looping code explicitly checks a real-time clock.

pax is an archiving utility available for various operating systems and defined since 1995. Rather than sort out the incompatible options that have crept up between tar and cpio, along with their implementations across various versions of Unix, the IEEE designed new archive utility pax that could support various archive formats with useful options from both archivers. The pax command is available on Unix and Unix-like operating systems and on IBM i, and Microsoft Windows NT until Windows 2000.

stat (system call) Unix system call

stat is a Unix system call that returns file attributes about an inode. The semantics of stat vary between operating systems. As an example, Unix command ls uses this system call to retrieve information on files that includes:

Interix was an optional, POSIX-conformant Unix subsystem for Windows NT operating systems. Interix was a component of Windows Services for UNIX, and a superset of the Microsoft POSIX subsystem. Like the POSIX subsystem, Interix was an environment subsystem for the NT kernel. It included numerous open source utility software programs and libraries. Interix was originally developed and sold as OpenNT until purchased by Microsoft in 1999.

In computer science, a readers–writer is a synchronization primitive that solves one of the readers–writers problems. An RW lock allows concurrent access for read-only operations, whereas write operations require exclusive access. This means that multiple threads can read the data in parallel but an exclusive lock is needed for writing or modifying data. When a writer is writing the data, all other writers and readers will be blocked until the writer is finished writing. A common use might be to control access to a data structure in memory that cannot be updated atomically and is invalid until the update is complete.

In parallel computing, a barrier is a type of synchronization method. A barrier for a group of threads or processes in the source code means any thread/process must stop at this point and cannot proceed until all other threads/processes reach this barrier.

setcontext is one of a family of C library functions used for context control. The setcontext family allows the implementation in C of advanced control flow patterns such as iterators, fibers, and coroutines. They may be viewed as an advanced version of setjmp/longjmp; whereas the latter allows only a single non-local jump up the stack, setcontext allows the creation of multiple cooperative threads of control, each with its own stack.

<span class="mw-page-title-main">CPU time</span> Time used by a computer

CPU time is the amount of time for which a central processing unit (CPU) was used for processing instructions of a computer program or operating system, as opposed to elapsed time, which includes for example, waiting for input/output (I/O) operations or entering low-power (idle) mode. The CPU time is measured in clock ticks or seconds. Often, it is useful to measure CPU time as a percentage of the CPU's capacity, which is called the CPU usage. CPU time and CPU usage have two main uses.

stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. It provides facilities for stepping through a list of function arguments of unknown number and type. C++ provides this functionality in the header cstdarg.

select is a system call and application programming interface (API) in Unix-like and POSIX-compliant operating systems for examining the status of file descriptors of open input/output channels. The select system call is similar to the poll facility introduced in UNIX System V and later operating systems. However, with the c10k problem, both select and poll have been superseded by the likes of kqueue, epoll, /dev/poll and I/O completion ports.

Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum of effort. Unlike JNI, no boilerplate or generated glue code is required.

<span class="mw-page-title-main">Microsoft POSIX subsystem</span> Subsystem shipped with the first versions of Windows NT

Microsoft POSIX subsystem is one of four subsystems shipped with the first versions of Windows NT, the other three being the Win32 subsystem which provided the primary API for Windows NT, plus the OS/2 and security subsystems.

Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.

References

  1. "libc/bionic/pthread.c - platform/bionic - Git at Google". android.googlesource.com.
  2. "Pthread Win-32: Level of standards conformance". 2006-12-22. Archived from the original on 2010-06-11. Retrieved 2010-08-29.
  3. "pthread.h(0p) — Linux manual page" . Retrieved 18 December 2022.
  4. Hart, Johnson M. (2004-11-21). "Experiments with the Open Source Pthreads Library and Some Comments". Archived from the original on 2010-08-30. Retrieved 2010-08-29.
  5. File: pthreads4w-code-v3.0.0.zip – Source for pthreads4w v3.0.0
  6. File: pthreads4w-code-v2.11.0.zip – Source for pthreads4w v2.11.0
  7. see http://locklessinc.com/articles/pthreads_on_windows which is where it was originally derived from
  8. "Chapter 1: Introduction to Windows Services for UNIX 3.5". 5 December 2007.

Further reading