Created
October 26, 2018 21:11
-
-
Save houqp/cbb570cd128b73dab49ca8f1cd2dedf3 to your computer and use it in GitHub Desktop.
python linux file 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
def unsafe_function(): | |
print('ONLY RUN ME ONCE!') | |
first = True | |
lock = open('foo', 'w+') | |
while True: | |
try: | |
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
if first: | |
unsafe_function() | |
fcntl.flock(x, fcntl.LOCK_UN) | |
break | |
except IOError as e: | |
# raise on unrelated IOErrors | |
if e.errno != errno.EAGAIN: | |
raise | |
else: | |
first = False | |
time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment