Multithreading in C Tutorial - Part 2(pthread_self)

Each thread created using pthread_create api is assigned an unique id.After the pthread_create is executed successfully,the parent can get the thread id,but what if we want to know the id of the thread while it is in execution,this can be achieved by calling a function pthread_self()

Look at the example code to understand:

app.c:


#include <stdio.h>
#include <pthread.h>

void *thread_fn(void *arg)
{

sleep(1);
printf("ID of thread in thread_fn is %u\n",pthread_self());
return NULL;
}



int main(int argc, char *argv[])
{

pthread_t tid;
printf("In Main Fn\n");
pthread_create(&tid, NULL, thread_fn, NULL);
printf("ID of thread in main:%u\n",tid);
pthread_join(tid, NULL);
printf("After the thread execution\n");
return 0;

}

In order to compile this application you have to pass -lpthread as an argument to gcc

gcc pthread_self.c -0 pthread_self -lpthread


O/P:

In Main Fn
ID of thread in main:3076332352
ID of thread in thread_fn is 3076332352

After the thread execution

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig