多进程将无法在Jupyter Notebook的Windows上并行运行

时间:2019-02-02 02:37:46

标签: python python-2.7 jupyter-notebook python-multiprocessing

我目前正在使用jupyter笔记本电脑在Windows上工作,并且一直在努力使多处理工作正常。它不会并行运行我所有的异步程序,而是一次运行一个异步程序,请提供一些指导以解决我的问题。我需要将结果放入变量中,以备将来使用。我不明白什么?

import multiprocessing as mp
import cylib
Pool = mp.Pool(processes=4)
result1 = Pool.apply_async(cylib.f, [v]) # evaluate asynchronously 
result2 = Pool.apply_async(cylib.f, [x]) # evaluate asynchronously
result3 = Pool.apply_async(cylib.f, [y]) # evaluate asynchronously 
result4 = Pool.apply_async(cylib.f, [z]) # evaluate asynchronously

vr = result1.get(timeout=420) 
xr = result2.get(timeout=420)
yr = result3.get(timeout=420) 
zr = result4.get(timeout=420)

1 个答案:

答案 0 :(得分:1)

任务正在并行执行。

但是,这是同步获取结果的,即“等到result1准备好,然后等到result2准备好,..”等等。

vr = result1.get(timeout=420) 
xr = result2.get(timeout=420)
yr = result3.get(timeout=420) 
zr = result4.get(timeout=420)

考虑以下示例代码,其中异步轮询每个任务

from time import sleep
import multiprocessing as mp
pool = mp.Pool(processes=4)

# Create tasks with longer wait first
tasks = {i: pool.apply_async(sleep, [t]) for i, t in enumerate(reversed(range(3)))}
done = set()


# Keep polling until all tasks complete
while len(done) < len(tasks):

    for i, t in tasks.items():

        # Skip completed tasks
        if i in done:
            continue

        result = None

        try:
            result = t.get(timeout=0)
        except mp.TimeoutError:
            pass
        else:
            print("Task #:{} complete".format(i))
            done.add(i)

您可以复制上述内容,也可以在apply_async上使用callback参数在任务完成时自动执行一些处理。