from weakref import WeakValueDictionary import weakref import gc gc.set_threshold(1, 1, 1) class C(object): def __init__(self, i): self.i = i self.loop = self def fiddle(self): if not hasattr(self, 'i'): raise SystemError('ack! %s %s' % (id(self), weakref.getweakrefcount(self))) class Registry(object): def __init__(self): self.all = WeakValueDictionary() def register(self, conns): for x in conns: self.all[id(x)] = x def fiddle(self): for c in self.all.values(): c.fiddle() registry = Registry() import random import threading mutex = threading.Lock() class Worker(threading.Thread): def __init__(self, tid): threading.Thread.__init__(self) self.tid = tid def run(self): i = 0 tid = self.tid while True: i += 1 #mutex.acquire() conns = [C(j) for j in range(50)] #mutex.release() mutex.acquire() registry.register(conns) mutex.release() print "%d+%d" % (tid, i), if random.random() < 0.2: mutex.acquire() registry.fiddle() mutex.release() ts = [Worker(tid) for tid in range(3)] for t in ts: t.start()