×

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently.

Using pthreads, you can create a new thread and specify a function for the thread to execute. The threads can be created and managed independently of each other, and they can run concurrently, allowing your program to perform multiple tasks simultaneously.

Example 1:

Here is an example of how to create a new thread using threads in C++:

#include <pthread.h>
#include <iostream>
void *print_message_function( void *ptr );
int main()  {
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
    int  iret1, iret2;
    /* Create independent threads each of which will execute function */
    iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
    if(iret1)   {
        std::cout<< "Error - pthread_create() return code: " << iret1 << std::endl;
        exit(EXIT_FAILURE);  }
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
    if(iret2)
    {
        std::cout<< "Error - pthread_create() return code: " << iret2 << std::endl;
        exit(EXIT_FAILURE);
    }
    std::cout<< "pthread_create() for thread 1 returns: " << iret1 << std::endl;
    std::cout<< "pthread_create() for thread 2 returns: " << iret2 << std::endl;
    /* Wait till threads are complete before main continues. Unless we  */
    /* wait we run the risk of executing an exit which will terminate   */
    /* the process and all threads before the threads have completed.   */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL); 
    exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
    char *message;
    message = (char *) ptr;
    std::cout<< message << std::endl;
}

This program creates two new threads, each executing the print_message_function. The main thread will wait for both threads to complete before exiting.

In C++, the pthread library allows you to create and manage threads.

To use pthread in your C++ program, you must include the <pthread.h> header file.

Example 2:

Here is an example of how to create a new thread using the pthread library:

#include <iostream>
#include <pthread.h>
void *thread_function(void *arg)
{
    std::cout<< "Hello from a new thread!" << std::endl;
    return NULL;
}
int main()
{
pthread_t thread;
    int ret = pthread_create(&thread, NULL, thread_function, NULL);
    if (ret != 0) {
        std::cout<< "Error: unable to create thread, " << ret << std::endl;
        return -1;
    }
pthread_join(thread, NULL);
    return 0;
}

This code creates a new thread and prints "Hello from a new thread!" to the console.

Parameters

The pthread_create function in C++ is used to create a new thread. It takes the following parameters:

  • pthread_t *thread: A pointer to a pthread_t variable that will be filled in with the thread identifier of the new thread.
  • constpthread_attr_t *attr: A pointer to a pthread_attr_t structure that specifies the attributes of the new thread. If this parameter is NULL, the default thread attributes will be used.
  • void *(*start_routine)(void *): A pointer to the function that the new thread will execute. This function should have a prototype of void *func(void *).
  • void *arg: A pointer to data that will be passed to the start routine as its argument.

Explanation:

A thread, a lightweight process, is a single flow of execution within a program. Threads are useful for parallelizing work, as they allow multiple pieces of code to be executed concurrently within a single program. pthread is a C library that provides support for creating and managing threads.

In C++, you can use the pthread library to create and manage threads by including the pthread.h header file and linking with the pthread library. The pthread_create function creates a new thread, and the pthread_join function waits for a thread to complete execution.

Example 3:

Here's an example of how to create a new thread using pthread_create:

#include <pthread.h>
void *print_message_function( void *ptr );
int main()
{
pthread_t thread1;
const char *message1 = "Thread 1";
     int  iret1;
     iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
     if(iret1) {
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
         exit(EXIT_FAILURE);}
pthread_join( thread1, NULL);
     exit(EXIT_SUCCESS);
void *print_message_function( void *ptr )
{
     char *message;
     message = (char *) ptr;
printf("%s \n", message);
}


In this example, the print_message_function is the start routine that the new thread will execute. The pthread_create function takes four parameters: a pointer to a pthread_t variable that will be filled in with the thread identifier of the new thread, a pointer to a pthread_attr_t structure that specifies the attributes of the new thread, a pointer to the start routine function, and a pointer to data that will be passed to the start routine as its argument. The pthread_join function is then used to wait for the new thread to complete execution before exiting the program.


Related Topics

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

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.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.