为什么 Multiprocessing Pool 方法会引发 TimeoutError?

Why does the Multiprocessing Pool method raise a TimeoutError?

我将其用作示例代码,但它被冻结了。我打开了任务管理器并查看了分配的资源。我可以看到 运行 代码前后进程数的变化,但我不明白为什么它会导致控制台冻结。 这只发生在 Spyder 中。如果我从命令行调用脚本,它会 运行 正常。

import multiprocessing as mp
def doubler(number):
   return number*2
if __name__=='__main__':    
    pool=mp.Pool(processes=3)
    arglist=[1,2,3]
    result=[pool.apply_async(doubler,(i,)) for i in arglist]
    for res in result:
        print(res.get())

我还使用了 documentation 中的示例代码,它引发了一个没有任何描述的 TimeoutError。 截图:TimeoutError

您在 windows 上的交互式解释器中似乎是 运行 这个。

文档中有a note about that

Note: Functionality within this package requires that the __main__ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.pool.Pool examples will not work in the interactive interpreter.

虽然它在某些情况下可以工作(如果 OS 支持 fork() 那么多处理可以使用 fork start method,但是 Windows 不),最好遵循该建议。