Skip to content

Instantly share code, notes, and snippets.

@houqp
Created October 26, 2018 21:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save houqp/cbb570cd128b73dab49ca8f1cd2dedf3 to your computer and use it in GitHub Desktop.
Save houqp/cbb570cd128b73dab49ca8f1cd2dedf3 to your computer and use it in GitHub Desktop.
python linux file lock
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