使用Pool.apply_async调用时,为什么传递Queue会导致此函数失败?

时间:2017-12-11 22:34:45

标签: python multiprocessing

当我将Queue对象传递给使用Pool.apply_async调用的函数时,该函数失败,如ApplyResult.successful()所示并且没有打印输出。在这种情况下,函数的主体似乎根本不运行。

我原本计划使用Queue将来自不同进程的结果集合同步为suggested by the multiprocessing documentation,但即使Queue实际上没有在函数中使用,Queue也会导致失败。

from multiprocessing import Pool, Queue
import time
from random import randint

def sample_function(name, results):
    delay_ms = randint(1, 10)
    print ("{} starting with delay {:d}".format(name, int(delay_ms)))
    time.sleep(delay_ms)
    # results argument is unused! 
    #results.put("{} result".format(name))
    print ("{} ending".format(name))

resultsQueue = Queue()
jobs = ['one','two','three','four', 'five', 'six']

pool = Pool(processes=4)
# fails
jobStatuses = [pool.apply_async(sample_function, args=(job, resultsQueue)) for job in jobs]
# succeeds
#jobStatuses = [pool.apply_async(sample_function, args=(job,'works with string argument')) for job in jobs]

pool.close()
print('closing: no more tasks')
pool.join()

for status in jobStatuses:
    print (status.ready(), status.successful())

while not resultsQueue.empty():
    print(resultsQueue.get())
print('All finished')

我可以在没有Pool.apply_async的情况下调用相同的函数,它会成功:sample_function('test without pool', resultsQueue)。我也可以用一个字符串调用Pool.apply_async函数,它会成功。

1 个答案:

答案 0 :(得分:3)

RuntimeErrorapply_async来电中出现multiprocessing.Queue for status in job_statuses: print(status.__dict__) Manager().Queue()会被忽略。
稍微改变你的代码我能够追踪它:

String

输出:

  

{' _value':RuntimeError('队列对象只应在进程之间通过继承共享',),' _success':False,' _callback':无,' _cache':{},' _job':0,' _error_callback':无,' _event': }

x6次。

使用可以在进程间共享的final Pattern pattern = Pattern.compile("(?<=abc)aa"); final Matcher matcher = pattern.matcher("abaca"); final String subMatch; if (matcher.find()) { subMatch = matcher.group(); } else { subMatch = ""; } System.out.println(subMatch); 来解决这个问题。