多进程 - 为什么python2.7中用Process创建子进程的语句之前必须加#if _name__ == '__main__'?
巴扎黑
巴扎黑 2017-04-17 16:05:22
[Python讨论组]
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."
巴扎黑
巴扎黑

全部回复(2)
阿神

我这运行没有提示错误,还有,怎么文不对题,,,

伊谢尔伦

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号