Get thread pid

Ove Svensson ove.svensson at
Mon Feb 2 11:01:12 CET 2009

Alejandro <alejandro.weinstein at> writes:

> On Jan 30, 1:40 pm, Christian Heimes <li... at> wrote:
>> May I ask why you want to get the TID?
> htop shows the TID of each thread. Knowing the TID allows me to know
> which thread is hogging the CPU. If there is a better way to do this,
> or there is something fundamentally wrong with this approach, please
> let me know.
> Alejandro.

Assuming we are talking about a  posix (pthread) architecture, 
you can't really say anything about the thread id (TID). Pthreads
identifies each thread with the anonymous type pthread_t. If you
want to write a portable application, you must not assume anything
regarding the real type. It could be an integer, pointer, struct
or something else. Just because some operating systems use an
integer for the pthread_t doesn't mean that others do the same.

It is true that the operating system must have some way to identify
each thread (within each process), but it is not visible or accessible
to the application.

If you have a threading *framework* on top of pthreads, which uses 
some TID, that is then either purely an artificial id or a non-portable 
architecture specific access to the operating system id. For example,
python thread.get_ident() returns the `thread identifier' of the 
current thread. That TID can be *anything*. You must not assume that
id has any meaning (other than being unique per thread). The python
class threading.Thread has methods setName() and getName() for
setting and fetching the *name* of a thread. That is a pure application
name and has nothing to do with the id used by the operating system.

The reason that python modules thread and threading doesn't return
any real TID is simply that there isn't any TID that it can return.
At least not in any portable way.

If you find a way to get to the real TID, that will be specific to
your architecture.

If htop (or any other application) returns a TID, that is either
artificial or architecture specific.

More information about the Python-list mailing list