Home » Linux, OS Concepts and Networking » Operating System Concepts » Create multiple threads, identify thread id of the current thread using pthread C library

Create multiple threads, identify thread id of the current thread using pthread C library

The pthread_self() function returns the ID of the calling thread. This is the same value that is returned in *thread in the pthread_create(3) call that created this thread. The pthread_equal() function compares two thread identifiers.

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
  
#define NUM_OF_THREADS 2
  
pthread_t thread_id[NUM_OF_THREADS];
  
void* shared_function_between_two_threads(void *arg) {
        unsigned long i = 0;
        pthread_t id = pthread_self();
  
        if(pthread_equal(id, thread_id[0]))
                printf("\n First thread processing\n");
        else
                printf("\n Second thread processing\n");
        return NULL;
}
  
int main(int argc, char **argv) {
        int i = 1;
        int err;
  
        for (i=0; i<NUM_OF_THREADS; i++) {
                err = pthread_create(&(thread_id[i]), NULL, &shared_function_between_two_threads, NULL);
                if (err != 0)
                        printf("Thread creation failed :[%s]", strerror(err));
                else
                        printf("Thread %ld created successfully\n", thread_id[i]);
        }
  
        printf("Waiting in main for thread to finish\n");
        for (i=0; i<NUM_OF_THREADS; i++) {
                pthread_join(thread_id[i], NULL);
        }
  
        printf("Thread execution finished, exiting from main program\n");
        return 0;
}


Now, lets compile this program on Linux command line using gcc as below, notice that we need to link the pthread library to get the above source code compiled.

$ gcc -o array_of_threads array_of_threads.c -lpthread

Now, lets execute this binary as,

$ ./array_of_threads
Thread -1210533056 created successfully

 First thread processing
Thread -1218925760 created successfully
Waiting in main for thread to finish

 Second thread processing
Thread execution finished, exiting from main program

As you can see above we created the threads and its showing the thread ids.


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment