Update: Putting f outside the class seems to make the example work as well.
My goal is:
- Create a class that processes tasks in a pool
- Create an instance, start the processes and monitor the progress
However I do not understand why the following code only works when calling time.sleep() after pool.close().
Minimum example:
import multiprocessing as mp
import time
class MultProc:
def __init__(self, n: int):
self.n = n
# Also works with putting function outside this class
def f(self, i: int, return_list):
time.sleep(5)
return_list.append(i)
def multiproc(self):
manager = mp.Manager()
self.return_list = manager.list()
pool = mp.Pool()
results = {}
for i in range(self.n):
results[i] = pool.apply_async(self.f, args=(i, self.return_list))
pool.close()
time.sleep(0.01) # Only works with this line
self.pool = pool
def main():
mult = MultProc(n=10)
mult.multiproc()
n = 0
while True:
n+=1
print(mult.return_list)
time.sleep(1)
if n > 20:
break
if __name__ == "__main__":
main()