I'm interested in using multi-processing to over-write a class member value and the do that repeatedly multiple times. In order to do then be able to write this to a file, I'm using queues as suggested in another SO answer. As a minimum reproducible example, consider the following:
import multiprocessing
N_CORES = 4
class FooPool(object):
def __init__(self):
self.l = 10 * [0]
def fn_populate(self):
self.l = [i for i in range(len(self.l))]
def fn_listen(self, q):
while True:
s = q.get()
if s[0] == 'kll': break
i, x = s
self.l[i] = x
with open('bar.txt', 'w') as fl: fl.write(f'{self.l}\n')
def fn_exec(self, i, q):
x = i ** 2
q.put([i, x])
def mp_exec(self, n_cores):
mp_manager = multiprocessing.Manager()
q = mp_manager.Queue()
with multiprocessing.Pool(processes=n_cores) as pool:
_ = pool.apply_async(self.fn_listen, (q,))
jobs = []
for i in range(10):
job = pool.apply_async(self.fn_exec, (i, q))
jobs.append(job)
for job in jobs:
job.get()
q.put(['kll', -1])
pool.close()
pool.join()
if __name__ == "__main__":
p = FooPool()
for _ in range(2): p.mp_exec(N_CORES)
Each index position of list self.l
is squared, copied to that same position in the list and then self.l
is written to a file.
Now, let's say I want to do this more than once; so in this example, what I would hope to see in my text-file is
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561]
instead it contains
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Further, p.l
remains a list of zeroes. Now, normally this list object of class is mutable (if that is even the right way of thinking about this, please correct me if I misunderstand). For example, calling p.fn_populate()
will "overwrite" the list, but it looks like every call to p.mp_exec
creates a new instance. This is confirmed in this other thread, but no solution is suggested.
How can I overcome this behaviour? For my specific case, I tried creating an object that will store all data that must persist, but this creates a huge overhead, and as a result the multiprocessing implementation seems to run slower than sequential execution.