×

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process flows. It accomplishes this by breaking the program into smaller jobs whose operations can be interspersed to execute concurrently.

A multithreaded program has two or more concurrently running components. In such a program, each component is referred to as a thread, so each thread specifies a unique path of execution.

There was no capability created for multithreaded applications before C++ 11. Instead, this feature is totally provided by the operating system.This article will teach you how to create multithreaded C++ programs using POSIX, assuming you are using the Linux operating system. On various Unix-like POSIX systems, including FreeBSD, NetBSD, GNU/Linux, Os X, and Solaris, POSIX Threads, or Pthreads, offers API.

Developing Threads

To construct a POSIX thread, use the syntax shown below.

#include <pthread.h>
pthread_create (thread1, attr1, start_routine1, arg1)

A new thread is created and made executable; in this case via pthread create. You can call this routine any number of times anywhere in your code. The parameters' description is as follows:

Thread: A secret, individual ID for such new thread that the function returned.

Attr: An object with an opaque attribute that can be used to modify thread attributes. A thread attributes objects can be specified or NULL for the default settings.

Start routine: The C++ program that the process will run after it has been established.

Arg: A coherent argument that starts routine may accept. It must be sent as a linked cast of type void and passed via reference. If no input is to be given, NULL may be used.

The maximum thread that a process may spawn depends on the implementation. Threads are peers once they are started, and peers can start new threads. No suggested hierarchy or interdependence exists between the threads.

Stopping Threads

The procedure listed below is used to end a POSIX thread. The pthread exit is used here to end a thread specifically. The pthread exit() procedure is often invoked when a thread has finished its task but is no longer needed.

Other threads will keep running even if main() exits with pthread exit() before all of the tasks it has spawned have finished. If not, they will be ended automatically after the main() is finished.

Ac++ program that creates multiple threads, and each thread increments the global variable. However, we see unexpected results. We expect that the value of the global variable will be the sum of all the increments done by each thread. But we are seeing the global variable increasing much more than the value we are expecting.

Example:

#include &lt;iostream&gt;
#include &lt;pthread.h&gt;
#include &lt;unistd.h&gt;
using namespace std;
int global = 0;
void *function(void *arg) {
cout<< "Thread id is " <<pthread_self() <<endl;
    for (int i = 0; i < 10000; i++) {
        global++;
    }
    return NULL;
}
int main() {
pthread_tthread_id;
    for (int i = 0; i < 5; i++) {
pthread_create(&thread_id, NULL, function, NULL);
    }
pthread_exit(NULL);
cout<< "Global value is " << global <<endl;
    return 0;
}

Output:

Pthreads or POSIX Threads in C++

Joining and Detaching Threads

Following are the two routines that can be used to join or detach threads:

pthread_join (threadid1, status) 
pthread_detach (threadid1)

The pthread join() method only blocks the caller thread until the specified 'threadid' thread exits. One of a thread's properties determines if it is actively recruiting or detached when it is created. You can only join topics that were made to be joinable. A separate thread cannot ever be joined after being formed.

Instead, we must use the pthread join command to bring all of the threads back into the original thread once they have completed their task to maintain our threads synchronised. The program will end once all the different threads have joined because the main thread will only exit once that happens.

The main goal of using Pthreads is to enhance program performance. A thread uses a lot lower operating system overhead than the cost of launching and managing a process. Compared to process management, thread management uses fewer system resources.


Related Topics

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.