I have a multiprocessing task that, in its simplest form, looks like the following:
def fun(x):
y = setup()
return y.f(x)
pool = mp.Pool(4)
pool.map(fun, my_list)
However, the setup() is expensive and so I only want to do it once in each process, as opposed to doing it once per item in my_list.
I also do not want to pickle y and send it into each process, in this instance I require that the setup occurs within each process separately.
Hence, I could do something like this to set up each process:
class MyProcess(mp.Process):
def __init__(self):
self.y = setup()
def fun(x):
return self.y.f(x)
workers = [MyProcess() for _ in range(4)]
Is there any way I can now use workers as if it was a Pool? i.e. mapping some worker's worker.fun to each item in my_list? Ideally, I would want something like this:
for result in workers.imap_unordered(MyProcess.fun, my_list):
# do something
I suspect a solution using a Queue would also work, but I'm not entirely sure how I can implement this.