8

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.

SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • The error message is telling you you cannot pass the synchronized object, i.e. `Tick` instances, as arguments. note, you are *not using threads* you are using *multiple processes* – juanpa.arrivillaga Jun 24 '19 at 20:07
  • @juanpa.arrivillaga i'm sorry I do not quite follow what you are trying to explain. Could you please add a bit more context? – SumNeuron Jun 25 '19 at 08:38
  • 1
    If you're seeing this error, consider [this answer](https://stackoverflow.com/a/58208695/) which uses `multiprocessing.Manager` which doesn't have this issue at all. – Asclepius Oct 03 '19 at 14:56

0 Answers0