Created
January 21, 2019 16:04
-
-
Save kgaughan/5cf3832cf0f8332aab4ce2da08f38692 to your computer and use it in GitHub Desktop.
Treating a script as its own mutex lock.
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 contextlib | |
import fcntl | |
import time | |
class MutexException(Exception): | |
""" | |
Failed to lock a file. | |
""" | |
@contextlib.contextmanager | |
def mutex(filename): | |
with open(filename, 'r') as fh: | |
try: | |
try: | |
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
except IOError: | |
raise MutexException("Failed to lock {}".format(filename)) | |
yield | |
finally: | |
fcntl.flock(fh, fcntl.LOCK_UN) | |
def main(): | |
with mutex(__file__): | |
time.sleep(5) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment