Python 当使用Pool.apply\u async调用此函数时,为什么传递队列会导致此函数失败?
当我将队列对象传递给使用Pool.apply\u async调用的函数时,该函数失败,如Python 当使用Pool.apply\u async调用此函数时,为什么传递队列会导致此函数失败?,python,multiprocessing,Python,Multiprocessing,当我将队列对象传递给使用Pool.apply\u async调用的函数时,该函数失败,如ApplyResult.successful()和缺少打印输出所示。在这种情况下,函数体似乎根本不运行 我曾计划使用队列来同步来自不同进程的结果的收集,但队列会导致失败,即使它实际上没有在函数中使用 from multiprocessing import Pool, Queue import time from random import randint def sample_function(name,
ApplyResult.successful()
和缺少打印输出所示。在这种情况下,函数体似乎根本不运行
我曾计划使用队列来同步来自不同进程的结果的收集,但队列会导致失败,即使它实际上没有在函数中使用
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')
我可以在没有
池的情况下调用同一个函数。应用异步将成功:sample\u函数('testwithout Pool',resultsQueue)
。我还可以使用字符串调用Pool.apply_async
函数,它将成功 在每个apply\u async
调用中都会发生运行时错误,而多处理.Queue
会被静默。
稍微更改一下您的代码,我就能够跟踪它:
for status in job_statuses:
print(status.__dict__)
输出:
{“U值”:RuntimeError(“队列对象只能通过继承在进程之间共享”),“_成功”:False,“_回调”:None,“_缓存”:{},“_作业”:0,“_错误”_回调”:None,“_事件”:}”
x6次
使用可在进程之间共享的Manager().Queue()
可以解决此问题。在每个apply\u async
调用中都会出现运行时错误,而多处理.Queue
会被静音。
稍微更改一下您的代码,我就能够跟踪它:
for status in job_statuses:
print(status.__dict__)
输出:
{“U值”:RuntimeError(“队列对象只能通过继承在进程之间共享”),“_成功”:False,“_回调”:None,“_缓存”:{},“_作业”:0,“_错误”_回调”:None,“_事件”:}”
x6次
使用可在进程之间共享的Manager().Queue()
可以解决此问题