Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@steinnes
Created May 15, 2016 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steinnes/e668dcd538873475f7ba8825fdc7c141 to your computer and use it in GitHub Desktop.
Save steinnes/e668dcd538873475f7ba8825fdc7c141 to your computer and use it in GitHub Desktop.
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