为什么python2.7中用Process创建子进程的语句之前必须加#if

from multiprocessing import Process 
import os 

def run(name): 
print 'The child process '%s' (pid %d) is running' % (name, os.getpid()) 
return 

print 'The parent process(pid %d) is running' % os.getpid() 
p = Process(target=run, args = ('test', )) 
print 'The child process is ready to run!' 
p.start(); 
p.join(); 
print 'The child process ends!' 

这段程序运行就会提示错误 

"Attempt to start a new process before the current process 
has finished its bootstrapping phase." 

这是 Windows 上多进程的实现问题。在 Windows 上,子进程会自动 import 启动它的这个文件,而在 import 的时候是会执行这些语句的。如果你这么写的话就会无限递归创建子进程报错。所以必须把创建子进程的部分用那个 if 判断保护起来,import 的时候 __name__ 不是 __main__ ,就不会递归运行了。

转载于:https://www.cnblogs.com/ExMan/p/10143807.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值