×

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

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

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

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

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

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.

C++ Continue in for 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.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

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

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.