这是一个简单的工人:
def mycube(x):
print('start {}'.format(x))
time.sleep(1)
print('end {}'.format(x))
return x**3
我们当然可以使用旧方法:
def test_apply_async0c():
results=[]
pool = multiprocessing.Pool(5)
[pool.apply_async(mycube, args=(x,), callback=lambda x: results.append(x)) for x in range(1, 7)]
pool.close()
pool.join()
print('all done!')
或者使用新方法,但不执行回调:
def test_apply_async0():
with multiprocessing.Pool(5) as pool:
results = [pool.apply_async(mycube, args=(x,)) for x in range(1, 7)]
print([_res.get() for _res in results])
print('all done!')
但是,我不能将上下文与pool.join一起使用,并且上下文不会自动加入,无论如何,我可以告诉上下文在超出范围之前加入吗?
def test_apply_async0b():
results=[]
with multiprocessing.Pool(5) as pool:
[pool.apply_async(mycube, args=(x,), callback=lambda x: results.append(x)) for x in range(1, 7)]
pool.join() # this does not work since the pool has not close yet?
print('all done!')