为什么多重处理调用的函数不打印消息? [英] Why function called by multiprocessing is not printing the messages?

查看:73
本文介绍了为什么多重处理调用的函数不打印消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在下面的示例中,myFunct()不打印任何消息,但该消息在通过多重处理"运行时却应该发送?以及如何解决?

Why in the example below myFunct() is not printing any messages is supposed to when it is ran by 'multiprocessing'? And how to solve it?

import multiprocessing as mp
poolDict=mp.Manager().dict()

def myFunct(arg):
    print 'myFunct():', arg
    for i in range(110):
        for n in range(500000):
            pass
        poolDict[arg]=i
    print 'myFunct(): completed', arg, poolDict


from multiprocessing import Pool
pool = Pool(processes=2)
myArgsList=['arg1','arg2','arg3']

pool.map_async( myFunct, myArgsList)
print 'completed'

推荐答案

这不是打印,因为主进程在调用map_async之后立即退出,因此所有子进程都没有机会实际运行.如果让脚本等待子进程完成,它将按预期打印:

This isn't printing because the main process is exiting immediately after calling map_async, so none of the child processes have a chance to actually run. It prints as expected if you make the script wait for the children to finish:

pool.map_async( myFunct, myArgsList)
pool.close()
pool.join()
print 'completed'

bash提示中的输出:

Output from bash prompt:

dan@dan:~> ./mult.py 
myFunct(): arg1
myFunct(): arg2
myFunct(): completed arg2 {'arg1': 108, 'arg2': 109}
myFunct(): arg3
myFunct(): completed arg1 {'arg1': 109, 'arg2': 109}
myFunct(): completed arg3 {'arg1': 109, 'arg2': 109, 'arg3': 109}
completed

这篇关于为什么多重处理调用的函数不打印消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆