Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python threading lock example
import threading
import time
from functools import wraps
FN_LOCKS = {}
class Lock(object):
def __init__(self, func_id):
global FN_LOCKS
if func_id in FN_LOCKS:
self.lock = FN_LOCKS[func_id]
else:
self.lock = threading.Lock()
FN_LOCKS[func_id] = self.lock
def __enter__(self):
self.lock.acquire()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.lock.release()
def synchronize(fn):
@wraps(fn)
def decorated(*args, **kwargs):
with Lock(id(fn)):
ret = fn(*args, **kwargs)
return ret
return decorated
counter = 0
@synchronize
def increment_and_print():
global counter
time.sleep(counter)
counter += 1
print counter
threads = []
for i in range(10):
print "Starting thread {}".format(i)
t = threading.Thread(target=increment_and_print)
t.start()
threads.append(t)
for t in threads:
t.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment