简体   繁体   中英

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM