Tuesday, August 13, 2013

Getting the Thread ID In C

As we have see in the pthread_self(),the ID is implemented or maintained by threading implementation not by the kernel,so for getting the unique ID assiged by the kernel we have to use the system call...
Take a look at the example...
void* printid(void *ptr)
printf("The id of %s is %u\n",(char*)ptr,syscall( __NR_gettid ));
int main()
    pthread_t thread[5];
    char *msg[]={"thread1","thread2","thread3","thread4","thread5"};
    int i;
    return 0;
On my system the output is:
The id of thread1 is 18622
The id of thread2 is 18623
The id of thread3 is 18624
The id of thread4 is 18625
The id of thread5 is 18626
As you can see now the IDs are different because they are assigned by the kernel not by the threading implementation...