Created
October 16, 2021 16:21
-
-
Save ganesh-k13/f8a9c09192841570033c69ffa4665e8d to your computer and use it in GitHub Desktop.
Locking decorator in python
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
# 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