ozn*_*ozn 54 python multiprocessing threadpool python-3.x python-multiprocessing
请告诉我之间的差异ThreadPool,并Pool在multiprocessing模块.当我尝试我的代码时,这是我看到的主要区别:
from multiprocessing import Pool
import os, time
print("hi outside of main()")
def hello(x):
print("inside hello()")
print("Proccess id: ", os.getpid())
time.sleep(3)
return x*x
if __name__ == "__main__":
p = Pool(5)
pool_output = p.map(hello, range(3))
print(pool_output)
Run Code Online (Sandbox Code Playgroud)
我看到以下输出:
hi outside of main()
hi outside of main()
hi outside of main()
hi outside of main()
hi outside of main()
hi outside of main()
inside hello()
Proccess id: 13268
inside hello()
Proccess id: 11104
inside hello()
Proccess id: 13064
[0, 1, 4]
Run Code Online (Sandbox Code Playgroud)
使用"ThreadPool":
from multiprocessing.pool import ThreadPool
import os, time
print("hi outside of main()")
def hello(x):
print("inside hello()")
print("Proccess id: ", os.getpid())
time.sleep(3)
return x*x
if __name__ == "__main__":
p = ThreadPool(5)
pool_output = p.map(hello, range(3))
print(pool_output)
Run Code Online (Sandbox Code Playgroud)
我看到以下输出:
hi outside of main()
inside hello()
inside hello()
Proccess id: 15204
Proccess id: 15204
inside hello()
Proccess id: 15204
[0, 1, 4]
Run Code Online (Sandbox Code Playgroud)
我的问题是:
为什么"outside __main __()"每次都在运行Pool?
multiprocessing.pool.ThreadPool不会产生新的流程?它只是创建新线程?
如果是这样,使用multiprocessing.pool.ThreadPool而不仅仅是threading模块之间的区别是什么?
我没有看到任何ThreadPool地方的官方文档,有人可以帮助我找到它吗?
nox*_*fox 68
该multiprocessing.pool.ThreadPool行为与相同multiprocessing.Pool与使用线程,而不是进程运行的工人逻辑的唯一区别.
你看到的原因
hi outside of main()
Run Code Online (Sandbox Code Playgroud)
被打印多次multiprocessing.Pool是由于池将产生 5个独立的进程.每个进程都将初始化自己的Python解释器并加载模块,从而导致顶层print再次执行.
请注意,仅当使用spawn进程创建方法时才会发生这种情况(仅在Windows上可用的方法).如果您使用那个fork(Unix),您将看到仅为线程打印一次消息.
将multiprocessing.pool.ThreadPool作为其实现从未完成未记录.它缺乏测试和文档.您可以在源代码中看到它的实现.
我相信下一个自然的问题是:何时使用基于线程的池以及何时使用基于进程的池?
经验法则是:
multiprocessing.pool.ThreadPoolmultiprocessing.Poolmultiprocessing.Pool由于流程隔离带来的优势在Python 3上,您可能希望了解concurrent.future.Executor池实现.