pthread c++ example with output
#include <iostream>
#include <pthread.h>
#define NUM_THREADS 5
void PrintHello(void threadid) {
long tid;
tid = (long)threadid;
std::cout << "Hello World! Thread ID, " << tid << std::endl;
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t = 0; t < NUM_THREADS; t++) {
std::cout << "Creating thread, " << t << std::endl;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc) {
std::cout << "Error: unable to create thread, " << rc << std::endl;
exit(-1);
}
}
pthread_exit(NULL);
}
Explanation:
#include <iostream>
and#include <pthread.h>
: Includes the necessary libraries for input/output and POSIX threads.#define NUM_THREADS 5
: Defines the number of threads to be created as 5.
The function void PrintHello(void threadid)
is the function that will be executed by each thread:
void PrintHello(void threadid)
: This function takes a void pointer as an argument and casts it to a long variabletid
. This function prints "Hello World! Thread ID" followed by thetid
value and exits the thread.
In the main()
function:
pthread_t threads[NUM_THREADS];
: Declares an array of pthreads to hold thread IDs.int rc;
andlong t;
: Declare variables for error checking and loop iteration.for(t = 0; t < NUM_THREADS; t++)
: Loops to create multiple threads.std::cout << "Creating thread, " << t << std::endl;
: Outputs the message indicating the creation of a thread with its respective ID.rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
: Creates a new thread withpthread_create
passing the thread ID, attributes (NULL for default), function to be executed (PrintHello
), and the argumentt
.if (rc) { std::cout << "Error: unable to create thread, " << rc << std::endl; exit(-1); }
: Checks if thread creation fails and prints an error message with the return code.pthread_exit(NULL);
: Exits the main thread after all threads are created.