What's the difference between ThreadPool vs Pool in the multiprocessing module?

前端 未结 1 1316
无人及你
无人及你 2020-12-07 10:25

Whats the difference between ThreadPool and Pool in multiprocessing module. When I try my code out, this is the main difference I see

相关标签:
1条回答
  • 2020-12-07 10:51

    The multiprocessing.pool.ThreadPool behaves the same as the multiprocessing.Pool with the only difference that uses threads instead of processes to run the workers logic.

    The reason you see

    hi outside of main()
    

    being printed multiple times with the multiprocessing.Pool is due to the fact that the pool will spawn 5 independent processes. Each process will initialize its own Python interpreter and load the module resulting in the top level print being executed again.

    Note that this happens only if the spawn process creation method is used (only method available on Windows). If you use the fork one (Unix), you will see the message printed only once as for the threads.

    The multiprocessing.pool.ThreadPool is not documented as its implementation has never been completed. It lacks tests and documentation. You can see its implementation in the source code.

    I believe the next natural question is: when to use a thread based pool and when to use a process based one?

    The rule of thumb is:

    • IO bound jobs -> multiprocessing.pool.ThreadPool
    • CPU bound jobs -> multiprocessing.Pool
    • Hybrid jobs -> depends on the workload, I usually prefer the multiprocessing.Pool due to the advantage process isolation brings

    On Python 3 you might want to take a look at the concurrent.future.Executor pool implementations.

    0 讨论(0)
提交回复
热议问题