I have some Python code that uses multiprocessing.pool.Pool.imap_unordered to create a bunch of temp files in parallel in a CPU-bound. Then I read the file names from the resulting iterator, process each one in a second disk-bound step, and delete them. Usually the disk-bound step is the faster of the two, so each temp file is processed and deleted before the next one is created. However, when running on a network filesystem, it's possible that the disk-bound step becomes the slow step, in which case the CPU-bound step running in parallel starts generating temp files faster than the disk-bound step can process and delete them, so a large number of temp files start accumulating. In order to avoid this problem, I'd like the parallel iteration to pause if it gets more than, say, 10 items ahead of the consumer. Is there any alternative to multiprocessing.pool.Pool.imap_unordered that can do this?
Here is some example code to simulate the issue:
import os
from time import sleep
from multiprocessing.pool import Pool
input_values = list(range(10))
def fast_step(x):
print("Running fast step for {x}".format(x=x))
return x
def slow_step(x):
print("Starting slow step for {x}".format(x=x))
sleep(1)
print("Finishing slow step for {x}".format(x=x))
return x
mypool = Pool(2)
step1_results = mypool.imap(fast_step, input_values)
for i in step1_results:
slow_step(i)
Running this produces something like:
$ python temp.py
Running fast step for 0
Running fast step for 1
Running fast step for 2
Running fast step for 3
Running fast step for 4
Starting slow step for 0
Running fast step for 5
Running fast step for 6
Running fast step for 7
Running fast step for 8
Running fast step for 9
Finishing slow step for 0
Starting slow step for 1
Finishing slow step for 1
Starting slow step for 2
Finishing slow step for 2
Starting slow step for 3
Finishing slow step for 3
Starting slow step for 4
Finishing slow step for 4
Starting slow step for 5
Finishing slow step for 5
Starting slow step for 6
Finishing slow step for 6
Starting slow step for 7
Finishing slow step for 7
Starting slow step for 8
Finishing slow step for 8
Starting slow step for 9
Finishing slow step for 9