Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created January 21, 2019 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgaughan/5cf3832cf0f8332aab4ce2da08f38692 to your computer and use it in GitHub Desktop.
Save kgaughan/5cf3832cf0f8332aab4ce2da08f38692 to your computer and use it in GitHub Desktop.
Treating a script as its own mutex lock.
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