为什么多处理调用的函数不打印消息?

时间:2014-05-30 18:37:08

标签: python multiprocessing

为什么在下面的示例中,myFunct()不会打印任何消息,因为它是由多处理'?运行的。以及如何解决?

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'

2 个答案:

答案 0 :(得分:2)

如果使用apply_async()而不是map_async()并添加close()和join()调用,它可以正常工作:

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.apply_async( myFunct, myArgsList)
pool.close()
pool.join()
print 'completed'

结果:

myFunct(): arg1
myFunct(): arg2
myFunct(): completedmyFunct(): completed arg1 {'arg1': 109, 'arg2': 109}
 arg2 {'arg1': 108, 'arg2': 109}
myFunct(): arg3
myFunct(): completed arg3 {'arg1': 109, 'arg2': 109, 'arg3': 109}
completed

答案 1 :(得分:1)

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

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

bash提示输出:

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