首页 > 解决方案 > 如何查看哪个进程拥有一个python线程

问题描述

我对多线程的理解是一个进程(cpu 核心)可以有多个线程运行。

到目前为止,在 python 中,当我想检查哪个线程正在调用函数时,我在函数内打印以下内容:

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

但这只会告诉我哪个线程。有没有办法也显示哪个进程拥有这个线程并打印它?

标签: pythonmultithreadingparallel-processingmultiprocessing

解决方案


线程归启动它们的进程所有。您可以使用 获取进程 ID os.getpid()

进程 ID 不会在线程之间改变:

>>> 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
>>>

如果您想知道哪个物理/逻辑 CPU 内核当前正在运行您的代码并且您在受支持的平台上,您可以使用 psutil 模块,如https://stackoverflow.com/a/56431370/51685中所述.


推荐阅读