I have a fairly simple class that resembles this:
class Tick:
def __init__():
self.val = Value('i', 0)
self.lock = Lock()
def tick(self):
self.lock().acquire()
try:
self.val.value = self.val.value + 1
finally:
self.lock.release()
and I want to use it with starmap:
def mp_tick(a, t):
t.tick()
tick = Tick()
with Pool(processes=4) as pool:
pool.starmap(mp_tick, [(i, tick) for i in range(100)]
which throws:
RuntimeError: Synchronized objects should only be shared between processes through inheritance
whereas:
def mp_tick(a):
tick.tick()
tick = Tick()
with Pool(processes=4) as pool:
pool.starmap(mp_tick, [(i, ) for i in range(100)]
does not. I know why the second works. I do not understand why the first fails.
Ideally, I wish to have an instance of Tick
that can be passed into multiple threads and have Tick
handle the lock and setting of its own value. I do not want a function to have to assume that a global variable exists.