测试进程沲和线程沲
为了和官方文档保持一致 ,这里把线程沲叫做 ThreadPool ,进程沲叫 multiprocessing.Pool。
线程沲(ThreadPool)
通过如下导入实现
- from multiprocessing.pool import ThreadPool
- from multiprocessing.dummy import Pool as ThreadPool
进程沲(multiprocessing.Pool)
通过如下导入实现
from multiprocessing import Pool
观察方法
在 ThreadPool 版本和 multiprocessing.Pool 版本的脚本执行期间,通过如下命令观察 python 进程数。
可以观察到,当 processes=8 时,ThreadPool 版本只有 1 个进程,而 multiprocessing.Pool 版本有 9 个进程。
- while true; do ps -ef|grep python|grep -v grep|grep -v denyhost; sleep 1;echo -e "--------\n"; done
-
-
- # pool = ThreadPool(processes=8)
- # ThreadPool 输出结果
- --------
- root 535648 525834 67 22:20 pts/1 00:00:07 python threading_ssh.py
- --------
- root 535648 525834 61 22:20 pts/1 00:00:07 python threading_ssh.py
- --------
-
-
- # pool = Pool(processes=8)
- # multiprocessing.Pool 输出结果
- --------
- root 536188 525834 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536191 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536192 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536193 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536194 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536195 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536196 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536197 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536198 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- --------
- root 536188 525834 6 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536191 536188 8 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536192 536188 3 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536193 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536194 536188 0 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536195 536188 9 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536196 536188 9 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536197 536188 4 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- root 536198 536188 9 22:21 pts/1 00:00:00 python multpRemoteCmd.py
- --------
multiprocessing.dummy
如下是 python 官方文档对 multiprocessing.dummy 的解释,multiprocessing.dummy 复制了 multiprocessing 的 API ,但是底层是通过封装 threading 模块来实现的。
multiprocessing.dummy replicates the API of multiprocessing but is no more than a wrapper around the threading module.