×

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

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.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 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.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

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.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Palindrome using For loop in C++

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++ also allows...

6 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.