首页 > 为什么python2.7中用Process创建子进程的语句之前必须加#if _name__ == '__main__'?

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

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__ ,就不会递归运行了。


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

【热门文章】
【热门文章】