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.


#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");
                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));
                        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 Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense Multimedia - Audio, Video, Images NDK / Middleware / HAL 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 User Interface Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question