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(void) {
        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;
}
 $ gcc -o array_of_threads array_of_threads.c -lpthread 
 $ $ ./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
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Content Management System - CMS Core Kernel C Programs Development Environment Setup Errors & Failures File Systems git Go Language Programs Hardware Platforms Home HTML JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply