'how to see which process owns a python thread

My understanding from multi-threading has been that one process (cpu core) can have multiple threads running with it.

So far in python when I want to check which thread is calling a function, I print the following inside the function:

print('current thread:', threading.current_thread())

but this only tells me which thread. Is there a way to also show which process owns this thread and print it?



Solution 1:[1]

Threads are owned by the process that starts them. You can get the process ID with os.getpid().

The process ID won't change between threads:

>>> import os
>>> import threading
>>>
>>> def print_process_id():
...   print(threading.current_thread(), os.getpid())
...
>>>
>>> threading.Thread(target=print_process_id).start()
<Thread(Thread-1, started 123145410715648)> 62999
>>> threading.Thread(target=print_process_id).start()
<Thread(Thread-2, started 123145410715648)> 62999
>>> threading.Thread(target=print_process_id).start()
<Thread(Thread-3, started 123145410715648)> 62999
>>> threading.Thread(target=print_process_id).start()
<Thread(Thread-4, started 123145410715648)> 62999
>>>

If you're looking to know which physical/logical CPU core is currently running your code and you're on a supported platform, you could use the psutil module, as described in https://stackoverflow.com/a/56431370/51685.

Solution 2:[2]

Threads are simply subset of a process.

The information associated with a thread are stored in what is called Thread Control Block (TCB). This contains the following information

  • Thread Identifier
  • Stack Pointer
  • Parent Process Pointer
  • Thread's register
  • Program counter

Since what you are interested in knowing is the process that the thread lives on.

import os
os.getpid()

Once you get the process id you can open the Task Manager or system monitor to get the name corresponding to the identifier gotten using os.getpid() Windows Task Manager Preview

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKX
Solution 2 FAYEMI BOLUWATIFE