我有一个非常简单的类,类似于此:
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()
并且我想将其与星图一起使用:
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)]
抛出:
RuntimeError: Synchronized objects should only be shared between processes through inheritance
而:
def mp_tick(a):
tick.tick()
tick = Tick()
with Pool(processes=4) as pool:
pool.starmap(mp_tick, [(i, ) for i in range(100)]
没有。我知道第二个为什么工作。我不明白为什么第一次失败。
理想情况下,我希望有一个Tick
实例,该实例可以传递到多个线程中,并让Tick
处理其自身值的锁定和设置。我不希望函数必须假定存在全局变量。