为什么 Python 在使用线程时启动许多进程
Why does Python launch many processes while using threading
我写了一个 Python 使用 threading.Thread
类 的程序。启动了大约 25 个线程。它是 运行 在 Raspberry Pi 4(4 核)上。
我在想只有 1 个 Python 进程会在使用线程时启动(因为 GIL)。看起来启动了 35 个进程。
top
表明 python3 使用 140% CPU。 (仅显示 1 个进程)
htop
显示许多 python3 个进程。他们加起来也达到了 140% 左右。
pstree -p
显示以下内容(仅 python 部分):
├─python3(28401)─┬─{python3}(28402)
│ ├─{python3}(28403)
│ ├─{python3}(28404)
│ ├─{python3}(28405)
│ ├─{python3}(28406)
│ ├─{python3}(28407)
│ ├─{python3}(28408)
│ ├─{python3}(28409)
│ ├─{python3}(28410)
│ ├─{python3}(28412)
│ ├─{python3}(28413)
│ ├─{python3}(28414)
│ ├─{python3}(28415)
│ ├─{python3}(28416)
│ ├─{python3}(28417)
│ ├─{python3}(28418)
│ ├─{python3}(28419)
│ ├─{python3}(28421)
│ ├─{python3}(28422)
│ ├─{python3}(28423)
│ ├─{python3}(28424)
│ ├─{python3}(28425)
│ ├─{python3}(28426)
│ ├─{python3}(28427)
│ ├─{python3}(28428)
│ ├─{python3}(28429)
│ ├─{python3}(28430)
│ ├─{python3}(28432)
│ ├─{python3}(28433)
│ ├─{python3}(28434)
│ ├─{python3}(28435)
│ ├─{python3}(28437)
│ ├─{python3}(28438)
│ ├─{python3}(28444)
│ └─{python3}(28445)
我的问题是如何解释这个?是否真的有很多进程 运行 并行意味着可以使用高达 300-400% CPU?还是一些 I/O 绑定工件?
Linux 中的线程对于某些工具来说看起来像是进程。这是因为随着时间的推移,线程从 进程演变 的方式。基本上,他们通过让进程能够共享相同的虚拟地址 space、相同的文件句柄等来创建 "threads,"。在某种意义上,实际上相同 "process" 中的不同 "threads" 是 个具有不同进程 ID 的不同进程。
如果您不想看到讨论帖,请尝试 pstree --hide-threads
。
我写了一个 Python 使用 threading.Thread
类 的程序。启动了大约 25 个线程。它是 运行 在 Raspberry Pi 4(4 核)上。
我在想只有 1 个 Python 进程会在使用线程时启动(因为 GIL)。看起来启动了 35 个进程。
top
表明 python3 使用 140% CPU。 (仅显示 1 个进程)
htop
显示许多 python3 个进程。他们加起来也达到了 140% 左右。
pstree -p
显示以下内容(仅 python 部分):
├─python3(28401)─┬─{python3}(28402)
│ ├─{python3}(28403)
│ ├─{python3}(28404)
│ ├─{python3}(28405)
│ ├─{python3}(28406)
│ ├─{python3}(28407)
│ ├─{python3}(28408)
│ ├─{python3}(28409)
│ ├─{python3}(28410)
│ ├─{python3}(28412)
│ ├─{python3}(28413)
│ ├─{python3}(28414)
│ ├─{python3}(28415)
│ ├─{python3}(28416)
│ ├─{python3}(28417)
│ ├─{python3}(28418)
│ ├─{python3}(28419)
│ ├─{python3}(28421)
│ ├─{python3}(28422)
│ ├─{python3}(28423)
│ ├─{python3}(28424)
│ ├─{python3}(28425)
│ ├─{python3}(28426)
│ ├─{python3}(28427)
│ ├─{python3}(28428)
│ ├─{python3}(28429)
│ ├─{python3}(28430)
│ ├─{python3}(28432)
│ ├─{python3}(28433)
│ ├─{python3}(28434)
│ ├─{python3}(28435)
│ ├─{python3}(28437)
│ ├─{python3}(28438)
│ ├─{python3}(28444)
│ └─{python3}(28445)
我的问题是如何解释这个?是否真的有很多进程 运行 并行意味着可以使用高达 300-400% CPU?还是一些 I/O 绑定工件?
Linux 中的线程对于某些工具来说看起来像是进程。这是因为随着时间的推移,线程从 进程演变 的方式。基本上,他们通过让进程能够共享相同的虚拟地址 space、相同的文件句柄等来创建 "threads,"。在某种意义上,实际上相同 "process" 中的不同 "threads" 是 个具有不同进程 ID 的不同进程。
如果您不想看到讨论帖,请尝试 pstree --hide-threads
。