×

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

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.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.