为什么即使代码已退出函数运行,子进程也无法完成?

2024-06-26 00:05:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的代码: 很明显,“成品”已经打印出来了。但还是要加入积木。 为什么会发生这种情况

from multiprocessing import Process
class MyProcess(Process):
    def run(self):
        ## do someting 
        print 'finished'       

processes = []
for i in range(3):
    p = MyProcess()
    p.start()
    processes.append(p)

for p in processes:
    p.join()

Tags: run代码infromimportfordef情况
2条回答

您应该添加这一行if __name__ == '__main__':,以使事情正常工作

说明: 您的主脚本将由process.py模块导入,然后它将执行您的脚本行2次,一次在导入期间执行,另一次在脚本执行期间执行

如果我们没有包括if __name__ == '__main__':,下面是运行时错误

RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

python 3.6中的工作代码是:

from multiprocessing import Process
class MyProcess(Process):
    def run(self):
        ## do someting 
        print ('finished')       

processes = []

if __name__ == '__main__':
    for i in range(3):
        p = MyProcess()
        p.start()
        processes.append(p)

    for p in processes:
        p.join()

    print('we are done here .......')

输出:

finished
finished
finished
we are done here .......

join如果任务完成,则不会阻塞,并且您的程序无效

for i in 3: # X integer is not iterable,
for i in range(3): # should be like this.

相关问题 更多 >