Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a thread's PID?

In the following code, I'm initiating a process with some worker function.

def listener(ttl, port):
    print "Started listenning on port: " + str(port) + " for: " + str(ttl) + " seconds."
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.bind(('localhost', port))
    serversocket.listen(1)
    time.sleep(ttl)
    print "Finished listening on port: " + str(port)

def main():
    thread1 = threading.Thread(target = listener, args = (20,5555))
    thread1.start()
    print thread1.get_ident()
    thread1.join()
    print "main completed"

How can I get a PID of thread1?

I'm on Ubuntu Linux 14.04 if that makes a difference.

like image 580
Naftaly Avatar asked Oct 17 '25 23:10

Naftaly


1 Answers

You can get a thread's PID with

thread.native_id

or the current one's PID with

threading.get_native_id()

NOTE: The native_id property and the get_native_id method are only supported in Python 3.8+