在Python多处理modu中,线程池和池有什么区别

2024-04-27 15:14:23 发布

您现在位置:Python中文网/ 问答频道 /正文

multiprocessing模块中ThreadPoolPool之间的区别是什么。当我尝试我的代码时,这是我看到的主要区别:

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)

我看到以下输出:

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]

使用“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)

我看到以下输出:

hi outside of main()
inside hello()
inside hello()
Proccess id:  15204
Proccess id:  15204
inside hello()
Proccess id:  15204
[0, 1, 4]

我的问题是:

  • 为什么每次在Pool中运行“outside\uu main”?

  • multiprocessing.pool.ThreadPool不产生新进程?它只是创造了新的线索?

  • 如果是这样的话,使用multiprocessing.pool.ThreadPool与使用threading模块有什么区别?

我在任何地方都看不到任何关于ThreadPool的官方文档,有人能帮我找到它吗?


Tags: ofimportidhelloosmainhimultiprocessing
1条回答
网友
1楼 · 发布于 2024-04-27 15:14:23

multiprocessing.pool.ThreadPool的行为与multiprocessing.Pool相同,唯一的区别是使用线程而不是进程来运行workers逻辑。

你看到的原因

hi outside of main()

使用multiprocessing.Pool多次打印是因为池将spawn5独立进程。每个进程将初始化自己的Python解释器并加载模块,从而再次执行顶层print

注意,只有在使用spawn进程创建方法(仅在Windows上可用的方法)时才会发生这种情况。如果您使用forkone(Unix),您将看到只打印一次线程的消息。

由于其实现从未完成,因此multiprocessing.pool.ThreadPool没有文档记录。它缺乏测试和文档。您可以在source code中看到它的实现。

我相信下一个自然的问题是:何时使用基于线程的池,何时使用基于进程的池?

经验法则是:

  • IO绑定作业->;multiprocessing.pool.ThreadPool
  • CPU绑定作业->;multiprocessing.Pool
  • 混合作业->;取决于工作负载,我通常更喜欢multiprocessing.Pool,因为流程隔离带来的优势

在Python 3上,您可能需要查看^{}池实现。

相关问题 更多 >