From f75cd0f2c9c09a026b4ca2a1b246c946f8d195f6 Mon Sep 17 00:00:00 2001 From: Orivej Desh Date: Fri, 12 Sep 2014 17:45:57 +0000 Subject: [PATCH] Fix race at exit. --- src/simpleflock.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/simpleflock.py b/src/simpleflock.py index 1fc2b8a..3565658 100644 --- a/src/simpleflock.py +++ b/src/simpleflock.py @@ -25,16 +25,12 @@ def __enter__(self): elif self._timeout is not None and time.time() > (start_lock_search + self._timeout): # Exceeded the user-specified timeout. raise - + # TODO It would be nice to avoid an arbitrary sleep here, but spinning # without a delay is also undesirable. time.sleep(0.1) def __exit__(self, *args): - fcntl.flock(self._fd, fcntl.LOCK_UN) - os.close(self._fd) - self._fd = None - # Try to remove the lock file, but don't try too hard because it is # unnecessary. This is mostly to help the user see whether a lock # exists by examining the filesystem. @@ -43,12 +39,13 @@ def __exit__(self, *args): except: pass + fcntl.flock(self._fd, fcntl.LOCK_UN) + os.close(self._fd) + self._fd = None + if __name__ == "__main__": print "Acquiring lock..." with SimpleFlock("locktest", 2): print "Lock acquired." time.sleep(3) print "Lock released." - - -