Get thread pid

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Jan 30 00:47:20 CET 2009


En Thu, 29 Jan 2009 14:04:49 -0200, Alejandro  
<alejandro.weinstein at gmail.com> escribió:

> I have Python program running under Linux, that create several
> threads, and I want to now the corresponding PID of the threads.
>
> In each of the threads I have
>
> def run(self):
>     pid = os.getpid()
>     logger.critical('process ID: %s', pid)
>
> However, the reported PID is the father number, not the PID of the new
> thread. Is there a way to get the PID of the thread?

Using "pid" for a thread identifier is confusing; I'd call it tid instead.  
(getpid() used to return a thread id in old Linux kernels, but that was a  
mess).

Try using Thread.ident (requires Python 2.6). I'd expect it to return  
gettid() but I've not checked it; from the docs, it might be a synthesized  
number as well.
<http://docs.python.org/library/threading.html#threading.Thread.ident>

In case it doesn't work, you can use ctypes to perform a gettid syscall.

-- 
Gabriel Genellina




More information about the Python-list mailing list