In this article we will discuss how to get thread id of a pthread and compare different thread ids.

How to get thread id of current thread

Use pthread_self() to get the current thread id i.e.

It returns the thread id as pthread_t object for the calling thread. As main function is also a thread, so we can also call pthread_self() form main function too. pthread_self() never fails and always returns the thread id.

Let’s see how to use it,

How to get thread id while creating thread

When we create a thread using pthread_create(), we pass the pointer of pthread_t as first argument. When thread is created it is set to thread id i.e.

Comparing 2 thread id (pthread_t) using pthread_equal

As pthread_t can be a structure, therefore we should not compare using == operator. POSIX provides a function pthread_equal() to compare 2 pthread_t i.e.

Lets see how to use it,

It returns 0 in case of failure and 1 in case they are equal.

Checkout complete example as follows,


To compile the above code use following command,

g++ example.cpp -lpthread



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.