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...
#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 ));
}
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:
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...

No comments:

Post a Comment

Feel free to comment......