Get thread pid

Jean-Paul Calderone exarkun at divmod.com
Fri Jan 30 12:10:55 EST 2009


On Fri, 30 Jan 2009 08:33:53 -0800 (PST), Alejandro <alejandro.weinstein at gmail.com> wrote:
>On Jan 30, 9:11 am, Jean-Paul Calderone <exar... at divmod.com> 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(9197)€ˆ€{python}(9555)
>             †€{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()))
    python(11427)───sh(11429)───pstree(11430)
    0
    >>> threading.Thread(target=time.sleep, args=(1000,)).start()
    >>> os.system("pstree -p " + str(os.getpid()))
    python(11427)─┬─sh(11436)───pstree(11437)
                  └─{python}(11431)
    0
    >>> ctypes.CDLL('libc.so.6').syscall(224)
    11427
    >>> 

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.

Jean-Paul



More information about the Python-list mailing list