Skip to content

Instantly share code, notes, and snippets.

@ganesh-k13
Created October 16, 2021 16:21
Show Gist options
  • Save ganesh-k13/f8a9c09192841570033c69ffa4665e8d to your computer and use it in GitHub Desktop.
Save ganesh-k13/f8a9c09192841570033c69ffa4665e8d to your computer and use it in GitHub Desktop.
Locking decorator in python
# imports
import threading
import typing
import functools
# Constants
class LockConstants:
PRINTLOCK = threading.Lock()
SOMEOTHERLOCK = threading.Lock()
def lock(lockname: threading.Lock):
def deco(f):
@functools.wraps(f)
def inner(*args, **kwargs):
with lockname:
return f(*args, **kwargs)
return inner
return deco
@lock(LockConstants.PRINTLOCK)
def print6() -> None:
for x in range(6):
print(f"Val: {x}")
if __name__ == "__main__":
t1=threading.Thread(target=print6)
t2=threading.Thread(target=print6)
t1.start()
t2.start()
t2.join()
t1.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment