Using pthread_self to find the thread id

Every thread created using pthread_create gets assigned a uniue thread id, with which it is recognized.

Note: Refer to creation of threads using pthreads in the post " "

The parent gets to know the thread id after the pthread_create is executed sucessfully, but while executing the thread if we want to access the thread id we have to use the function pthread_self.

The function pthread_self does not take any arguments, and returns the thread id, which is of kind pthread_t.

In the following program we are creating a thread which executes the function "hello". In the function "hello" we have used pthread_self to find out the thread id and then printed the same. Note that pthread_t is an unsigned long data type and hence we have to use %u while printing using printf.

Save the file as self_pthread.c

Compile it using gcc by passing the "-lpthread" flag.

We can see that the thread_id printed by the main function, parent, and the thread are the same, indicating that the value returned by pthread_self is the correct value.

No comments:

Post a Comment

Follow by Email