Created
January 14, 2019 13:32
-
-
Save draganHR/5c2ed4d4904d246ccfd5c31ca753088c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 fcntl | |
LOCK_SH = fcntl.LOCK_SH # shared lock | |
LOCK_NB = fcntl.LOCK_NB # non-blocking | |
LOCK_EX = fcntl.LOCK_EX | |
# django helpers | |
def _fd(f): | |
"""Get a filedescriptor from something which could be a file or an fd.""" | |
return f.fileno() if hasattr(f, 'fileno') else f | |
def lock(f, flags): | |
ret = fcntl.flock(_fd(f), flags) | |
return ret == 0 | |
def unlock(f): | |
ret = fcntl.flock(_fd(f), fcntl.LOCK_UN) | |
return ret == 0 | |
f = open('/tmp/mylock', 'w') | |
try: | |
lock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
except IOError as e: | |
print('failed to get lock') | |
else: | |
print('succeeded in getting lock') | |
# ... | |
unlock(f) | |
f.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment