python - 如何查看哪个进程拥有一个python线程
问题描述
我对多线程的理解是一个进程(cpu 核心)可以有多个线程运行。
到目前为止,在 python 中,当我想检查哪个线程正在调用函数时,我在函数内打印以下内容:
print('current thread:', threading.current_thread())
但这只会告诉我哪个线程。有没有办法也显示哪个进程拥有这个线程并打印它?
解决方案
线程归启动它们的进程所有。您可以使用 获取进程 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中所述.
推荐阅读
- python - 从QGIS中具有值关系小部件的字段中检索字符串
- python - 如何使用python解压缩和解压?
- sql - 文章奖品的 SQL SUM
- python - Pandas 应用函数,接收 KeyError 'Column Name'
- android - 从材料轮廓按钮更改颜色不起作用
- php - 带有集合一对一关系的嵌入表单的 Symfony 5 错误
- php - 为什么 JSON_UNESCAPED_LINE_TERMINATORS 没有取消我的换行符?
- javascript - 作为反应,将 onClick 从 Google Maps 中的标记传递到 app.js 时遇到问题
- android - 终止应用程序后未触发 AlarmManager 通知
- javascript - 如何为 Javascript 项目正确发布 SCSS 包