Tuesday, August 13, 2013

gettid() vs pthread_self()

So we have looked at both gettid(getting the id of the thread) and the pthread_self(),Now let us join then as see the output...so the difference between then is clear...

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<linux/unistd.h>
#include<sys/syscall.h>
void* printid(void *ptr)
{
printf("The id of %s is %u\n",(char*)ptr,syscall( __NR_gettid ));
printf("The id of %s is %u\n",(char*)ptr,(unsigned int)pthread_self());
}
int main()
{
    pthread_t thread[5];
    char *msg[]={"thread1","thread2","thread3","thread4","thread5"};
    int i;
    for(i=0;i<5;i++)
    {
        pthread_create(&thread[i],NULL,printid,(void*)msg[i]);
        pthread_join(thread[i],NULL);
    }
    return 0;
}
output:
The id of thread1 is 18799
The id of thread1 is 3086543760
The id of thread2 is 18800
The id of thread2 is 3086543760
The id of thread3 is 18801
The id of thread3 is 3086543760
The id of thread4 is 18802
The id of thread4 is 3086543760
The id of thread5 is 18803
The id of thread5 is 3086543760
Explanation:
As you can see the ID generated by pthread_self() is reused by the threading implementation after the thread completion which have achieved using the join in the for loop..and the ID assigned by the kernel is unique one...
So the difference between gettid() and the pthread_self() is:
1.)POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel.
2.)ID generated by the pthread_self() can be used after the completion of the thread but  the ID genereated by the kernel can't be used even after the completion of the thread..

1 comment:

  1. Superb! Thank you for the crystal clear explanation.

    ReplyDelete

Feel free to comment......