Sunday, August 5, 2012

Getting the Posix Thread Id in Linux

In linux system gettid function used to get the thread ID. The TID is diffrent than PID.In a single-threaded process, the TID is equal to the PID. But in a multithreaded program, all threads belonging to same process have the same PID but each one has a unique TID. The TID generally reprsent the kernel thread id and is different from the thread ID returned by pthread_self(i.e. thread handle which is returned from pthread_create function).

Note that Glibc does not provide the function gettid(). So we will use the system call to get the TID. Let's create a simple program to see the use of gettid, getpid and pthread_self. We'll call this threadBasic.c.

threadBasic.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <pthread.h>

pid_t gettid()
{
pid_t tid = syscall (SYS_gettid);
}

void* start_function(void* value)
{
pid_t tid = gettid();
printf("Thread start function is running for: %u\n", (unsigned int)pthread_self());
printf("The TID of thread is: %ld\n", (long int)tid);
printf("PID of parent process is: %d\n", getpid());
sleep(5);
pthread_exit(value);
}

main()
{
int res;
pthread_t thread1, thread2;
void* threadReturnValue;

printf("PID of main process: %d\n", getpid());

res = pthread_create(&thread1, NULL, start_function, "thread-one");
if (res != 0) {
perror("Creation of thread failed");
exit(EXIT_FAILURE);
}
printf("Thread1 created with id: %u\n", (unsigned int)thread1);

res = pthread_create(&thread2, NULL, start_function, "thread-two");
if (res != 0) {
perror("Creation of thread failed");
exit(EXIT_FAILURE);
}
printf("Thread2 created with id: %u\n", (unsigned int)thread2);

res = pthread_join(thread1, &threadReturnValue);
if (res != 0) {
perror("Joining of thread failed");
exit(EXIT_FAILURE);
}
printf("%s joined.\n", (char*)threadReturnValue);

res = pthread_join(thread2, &threadReturnValue);
if (res != 0) {
perror("Joining of thread failed");
exit(EXIT_FAILURE);
}
printf("%s joined.\n", (char*)threadReturnValue);
}

Now when you compile and run the program, you will see:

gcc -o threadBasic threadBasic.c -lpthread
./threadBasic
PID of main process: 4610
Thread1 created with id: 3078278000
Thread start function is running for: 3078278000
The TID of thread is: 4611
PID of parent process is: 4610
Thread start function is running for: 3069885296
The TID of thread is: 4612
Thread2 created with id: 3069885296
PID of parent process is: 4610
thread-one joined.
thread-two joined.

Explanation:

No comments:

Post a Comment