diff options
author | Frederick Yin <fkfd@fkfd.me> | 2021-10-27 09:31:04 +0800 |
---|---|---|
committer | Frederick Yin <fkfd@fkfd.me> | 2021-10-27 10:10:06 +0800 |
commit | 09bd022f5a713c24ab376f0d0901aba436dc151a (patch) | |
tree | 07aea89c37f1dd0927da9c56df36a7bb4e97932f /jimbrella/lockfile.py | |
parent | cbf419cb79f4a0d06c65167f81f10f503fff391d (diff) |
Separate Lockfile into new class
Diffstat (limited to 'jimbrella/lockfile.py')
-rw-r--r-- | jimbrella/lockfile.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/jimbrella/lockfile.py b/jimbrella/lockfile.py new file mode 100644 index 0000000..b898142 --- /dev/null +++ b/jimbrella/lockfile.py @@ -0,0 +1,33 @@ +import os + + +class Lockfile: + """Prevent unwanted concurrency for file I/O. + + For a file named "<file>", create or remove a lockfile named "<file>.lock". + + When a process is modifying the file, call `lock(). When the modification + is done, call `unlock()`. + """ + + def __init__(self, filepath): + self.filepath = filepath + self.lockpath = filepath + ".lock" + + def lock(self): + """Continue attempting to lock until locked.""" + locked = False + while not locked: + try: + f = open(self.lockpath, "x") + f.close() + locked = True + except FileExistsError: + continue + + def unlock(self): + """Remove lockfile.""" + try: + os.remove(self.lockpath) + except FileNotFoundError: + return |