Created
May 15, 2016 12:23
-
-
Save steinnes/e668dcd538873475f7ba8825fdc7c141 to your computer and use it in GitHub Desktop.
python threading lock example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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