This lock is more suitable for being a singleton or being an attribute of a singleton
import threading
import time
class ThreadLock(object):
def __init__(self):
self.namedlock = {}
self.lock = threading.Lock()
def __call__(self, name):
print 'name', name
self._name = name
with self.lock:
nlock = self.namedlock.setdefault(name, threading.Lock())
return nlock
def foo(args):
idx = args
name = 'hello' if idx != 0 else 'hi'
with my(name):
for i in range(10):
print 'thread-%d : %d' % (idx, i)
time.sleep(1)
my = ThreadLock()
for i in range(3):
threading.Thread(target = foo, args = (i,)).start()