Get thread pid

Jean-Paul Calderone exarkun at
Fri Jan 30 18:10:55 CET 2009

On Fri, 30 Jan 2009 08:33:53 -0800 (PST), Alejandro <alejandro.weinstein at> wrote:
>On Jan 30, 9:11 am, Jean-Paul Calderone <exar... at> wrote:
>> [clarification about threads]
>Thank you for the clarification. I will reformulate my question:
>pstree and also ntop (but not top) show a number for each thread, like
>for instance:
>$pstree -p 9197
>             †€{python}(9556)
>             †€{python}(9557)
>             †€{python}(9558)
>             †€{python}(9559)
>             †€{python}(9560)
>             †€{python}(9561)
>             †€{python}(9562)
>             †€{python}(9563)
>             „€{python}(9564)
>Is is possible to get the number corresponding to each thread?
>The reason I am interested is because one of my thread is hogging the
>CPU, and want to find which one is the culprit.

I think someone mentioned calling gettid using ctypes earlier in this
thread.  Unfortunately, this is somewhat convoluted:

    exarkun at charm:~$ python
    Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
    [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import ctypes, os, threading, time
    >>> os.system("pstree -p " + str(os.getpid()))
    >>> threading.Thread(target=time.sleep, args=(1000,)).start()
    >>> os.system("pstree -p " + str(os.getpid()))
    >>> ctypes.CDLL('').syscall(224)

224 comes from grepping /usr/include for SYS_gettid.  This is Linux
specific, and probably even architecture specific.  For a quick
debug hack, perhaps this is good enough, though.


More information about the Python-list mailing list