简体   繁体   English

使用多处理模块的简单玩具示例使计算机崩溃

[英]Simple toy example using multiprocessing module crashes computer

Trying the very simple following example causes my computer to grind to a halt, so that I have to restart. 尝试以下非常简单的示例会导致计算机停止运行,因此我必须重新启动。 Checking task manager shows hundreds of "python.exe" tasks: 检查任务管理器显示数百个“python.exe”任务:

import math
from multiprocessing import Pool

pool = Pool(processes=2)
print pool.map(math.sqrt, [1,4,9,16])

I am using a dual core cpu (i5 2467m) so I thought the above would be fine. 我使用的是双核cpu(i5 2467m)所以我认为以上都没问题。

I tried setting processes=1 , which causes a slightly different problem: the task never completes but it does not cause my computer to freeze up. 我尝试设置processes=1 ,这导致一个稍微不同的问题:任务永远不会完成,但它不会导致我的计算机冻结。

Any ideas? 有任何想法吗?

I had the same problem the first time I played around with multiprocessing . 我第一次玩multiprocessing时遇到了同样的问题。 Wrap the pool generation code in a if __name__ == '__main__' block. 将池生成代码包装在if __name__ == '__main__'块中。

import math
from multiprocessing import Pool

if __name__ == '__main__':
    pool = Pool(processes=2)
    print pool.map(math.sqrt, [1,4,9,16])

What's happening is that when the subprocess is created, your module is being unpickled and rerunning the pool generation code in an infinite recursion. 发生的事情是,在创建子进程时,您的模块正在进行unpickled并在无限递归中重新运行池生成代码。 With the if block, the spawning code will only run in the parent instance of the module. 使用if块,产生代码将仅在模块的父实例中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM