Я впервые пытаюсь реализовать многопроцессорность в своем коде python. Я застрял, так как я не могу заставить async_apply ждать завершения всех его процессов sh. Я хотел бы обработать элементы небольшими порциями и сохранить результаты, пока я go просматриваю длинный список элементов.
В качестве более простого примера:
import multiprocessing as mp
def fun(x, y):
print("here")
return(x+y)
buffer = []
for val in range(10):
buffer.append(val)
print(f{Added value: {val})
if len(buffer) == 5:
#It is my understanding, this is necessary on Windows
if __name__ == "__main__":
pool = mp.Pool()
res = [pool.apply_async(fun, args = (x,x)) for x in buffer]
res = [r.wait() for r in res]
print(f'Results: {res}')
buffer = []
pool.close()
pool.join()
Я бы хотел это приводит к следующему выводу:
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Here
Here
Here
Here
Here
Results: [0, 2, 4, 6, 8]
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Here
Here
Here
Here
Here
Results: [10, 12, 14, 16, 18]
Но фактически производит это (по крайней мере, на моей машине):
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Here
Here
Here
Here
Here
Results: [None, None, None, None, None]
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Added value: 0
Added value: 1
Added value: 2
Added value: 3
Added value: 4
Added value: 5
Added value: 6
Added value: 7
Added value: 8
Added value: 9
Here
Here
Here
Here
Here
Results: [None, None, None, None, None]
Любое предложение действительно приветствуется .