Tuesday, August 13, 2013

pthread_self()

Getting the Thread ID..
We can get the ID of the thread by using the funciton pthread_self() on the running thread.
The main point about this function is :It uniquely identifies EXISTING threads,Here EXISTINGhas a special meaning..The meaning is pthread_self() return the value which can be reused across the program that means if you have created a thread and it completed its execution then the id of that thread can be used as the id of another thread..
Let us prove the statement that is a thread completes then the id of that thread(returned by pthread_self) can be used as the id of another thread...
#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,(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:
On my system the output is:
The id of thread1 is 3086285712
The id of thread2 is 3086285712
The id of thread3 is 3086285712
The id of thread4 is 3086285712
The id of thread5 is 3086285712
As you can see the ID's of all the thread is equal...
Explanation:I need to explain only one thing that is how to make sure that a thread completes before the execution of the next thread the answer is simple joining the thread solves our purpose..so in the for loop we create a thread then call a join so the main program waits for the thread to complete for the next iteration of the for loop..In this way we can make sure that the thread starts after the completion of the previous thread...
As the thread completes so the program can use the same ID of thread1 for the thread2 and so on....
Why so???
POSIX thread IDs are assigned and maintained by the threading implementation not by the kernel,to get the ID assigned by the kernel see here...