Javatpoint Logo
Javatpoint Logo

POSIX Threads in OS

POSIX Threads are commonly known as PThreads. It is an execution model that exists independently from a language and a parallel execution model. It allows a program to control multiple different workflows that overlap in time. Each flow of work is referred to as a thread. Creation and controlling these flows is achieved by making calls to the POSIX Threads API. POSIX Threads is an API defined by the standard POSIX.1c, Threads extensions (IEEE Std 1003.1c-1995).

The API's implementation is available on many Unix-like POSIX-conformant operating systems such as FreeBSD, NetBSD, OpenBSD, Linux, macOS, Android, 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 many POSIX APIs and within third-party packages such as PThreads-w32, which implements PThreads on top of existing Windows API.

PThreads is a highly concrete multithreading system that is the UNIX system's default standard. PThreads is an abbreviation for POSIX threads, and POSIX is an abbreviation for Portable Operating System Interface, which is a type of interface that the operating system must implement. PThreads in POSIX outline the threading APIs that the operating system must provide.

PThreads works well on multiprocessor or multi-core systems, where the process flow may be scheduled to execute on another processor, increasing speed through parallel or distributed processing because the system does not create a new system, virtual memory space and environment for the process, threads needless overhead than forking or creating a new process.

PThread Headers

To use the PThread interfaces, we must include the header PThread.h at the start of the CPP script.

Why are PThreads Used?

Below are the following reasons to answer why PThreads is used in an operating system, such as:

  • The fundamental purpose for adopting PThreads is to improve program performance.
  • When compared to the cost of creating and managing a process, a thread can create with much less operating system overhead. Managing threads requires fewer system resources than managing processes.
  • All threads within a process share the same address space. Inter-thread communication is more efficient and easier to use than inter-process communication in many cases.
  • Threaded applications offer potential performance gains and practical advantages over non-threaded applications in several other ways:
  • Overlapping CPU work with I/O. For example, a program may have sections to perform a long I/O operation. While one thread is waiting for an I/O system call to complete, other threads can perform CPU's intensive work.
  • Priority/real-time scheduling tasks can be scheduled to supersede or interrupt lower priority tasks.
  • Asynchronous event handling tasks can interleave service events of indeterminate frequency and duration. For example, a web server can transfer data from previous requests and manage the arrival of new requests.
  • Multithreaded applications will work on a uni-processor system yet naturally take advantage of a multiprocessor system without recompiling.
  • In a multiprocessor environment, the most important reason for using PThreads is to take advantage of potential parallelism.
  • For a program to take advantage of PThreads, it must be organized into discrete, independent tasks that can execute concurrently.

Example

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 these four groups:

  • Thread management - creating, joining threads, etc.
  • Mutexes
  • Condition variables
  • Synchronizationbetween threads using read/write locks and barriers

The POSIX semaphore API works with POSIX threads but is not part of 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_. Below is an example illustrating the use of PThreads in C:

The above 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:

Output

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 second.
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 do not support the PThreads standard natively. Therefore the PThreads4w project seeks to provide a portable and open-source wrapper implementation. Also, it can be used to port UNIX software (which uses PThreads) with little or no modification to the Windows platform.

PThreads4w version 3.0.0 or later, released under the Apache Public License v2.0, is compatible with 64-bit or 32-bit Windows systems. Version 2.11.0, released under the LGPLv3 license, is also 64-bit or 32-bit compatible.

The Mingw-w64 project also contains a wrapper implementation of PThreads and winPThreads, which uses more native system calls than the PThreads4w project.

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/Win64 API but built directly on the operating system syscall interface.

Extended Tools in PThreads

Below is the list of extended tools available in PThreads, such as:/p>

  • Etnus Total View Supports thread debugging.
  • Smart GDB for Threads Debugging.
  • The debugger that comes with the DevProcompiler set from Sun understands threads.
  • Use the TNF utilities to trace, debug, and gather performance analysis information from your applications and libraries. The TNF utilities integrate trace information from the kernel, and multiple user processes and threads are especially useful for multithreaded code.
  • LockLintverifies the consistent use of mutex and readers/writer locks in multithreaded ANSI C programs. LockLint performs a static analysis of mutex and readers/writer locks and looks for inconsistent use of these locking techniques. In looking for inconsistent use of locks, LockLint detects the most common causes of data races and deadlocks.

Basic PThreads Library Calls

Below is the brief introduction of PThreads library calls, such as:

  • PThread_create: It creates a new thread, initializes its attributes, and makes it runnable.

The PThread_create subroutine creates a new thread and initializes its attributes using the attribute object specified by the attr parameter. The new thread inherits its creating thread's signal mask, but any pending signal of the creating thread will be cleared for the new thread.

The new thread is made runnable with the arg parameter and will execute the start_routine routine. The arg parameter is a void pointer to reference any data.

The PThread_create subroutine returns the new thread identifier via the thread argument. The caller can use this thread identifier to perform various operations on the thread. This identifier should be checked to ensure that the thread was successfully created.

  • void PThread_exit: It terminates the calling thread.

The PThread_exit subroutine terminates the calling thread safely and stores a termination status for any thread that may join the calling thread.

Unlike the exit subroutine, the PThread_exit subroutine does not close files. Thus any file opened and used only by the calling thread must be closed before calling this subroutine. Returning from the initial routine of a thread implicitly calls the PThread_exit subroutine, using the return value as a parameter.

  • PThread_t PThread_self(): It returns the calling thread's identifier.

The PThread_self subroutine returns the calling thread's identifier.

int PThread_join: The PThread_join subroutine blocks the calling thread until the thread specified in the call terminates. The target thread's termination status is returned in the status parameter.

The subroutine returns immediately if the target thread is already terminated but not detached yet. It is impossible to join a detached thread, even if it is not yet terminated. The target thread is automatically detached after all joined threads have been woken up.

This subroutine does not itself cause a thread to be terminated. It acts like the PThread_cond_wait subroutine to wait for a special condition.

  • int PThread_detach: It detaches the specified thread from the calling thread.

The PThread_detach subroutine indicates to the implementation that storage for the thread whose thread identifier is in the location thread can be reclaimed when that thread terminates. This storage shall be reclaimed on process exit, regardless of whether the thread has been detached or not, and may include storage for the thread return value.

If a thread has not yet terminated, PThread_detach shall not cause it to terminate. Multiple PThread_detach calls on the same target thread cause an error.

The subroutine returns immediately if the target thread is already terminated but not yet detached. It is impossible to join a detached thread, even if it is not yet terminated. The target thread is automatically detached after all joined threads have been woken up.

This subroutine does not itself cause a thread to be terminated. It acts like the PThread_cond_wait subroutine to wait for a special condition.

  • int PThread_mutex_init: It initializes a mutex and sets its attributes.

The PThread_mutex_init subroutine initializes a new mutex and sets its attributes according to the mutex attributes object attr. The mutex is initially unlocked.

After initializing the mutex, the mutex attributes object can be reused for another mutex initialization or deleted.

  • int PThread_mutex_destroy: It deletes a mutex.

The PThread_mutex_destroy subroutine deletes the mutex. After deleting the mutex, the mutex parameter is not valid until it is initialized again by a call to the PThread_mutex_init subroutine.

  • int PThread_mutex_lock: It locks a mutex.

The mutex object referenced by mutex is locked by calling PThread_mutex_lock. If the mutex is already locked, the calling thread blocks until the mutex becomes available. This operation returns with the mutex object referenced by mutex in the locked state with the calling thread.

  • int PThread_mutex_trylock: It tries to lock a Mutex.

The function PThread_mutex_trylock is identified to PThread_mutex_lock except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call returns immediately.

  • int PThread_mutex_unlock: It unlocks a Mutex.

The PThread_mutex_unlock function releases the mutex object. How a mutex is released is dependent upon the mutex's type attribute. If threads are blocked on the mutex object when PThread_mutex_unlock is called, then the mutex becomes available, and the scheduling policy is used to determine which thread shall acquire the mutex.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA