Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame^] | 1 | """ |
| 2 | Interprocess mutex based on file locks |
| 3 | """ |
| 4 | |
| 5 | import fcntl |
| 6 | import os |
| 7 | |
| 8 | class Lock: |
| 9 | |
| 10 | def __init__(self, filename): |
| 11 | self.filename = filename |
| 12 | # This will create it if it does not exist already |
| 13 | self.handle = open(filename, 'w') |
| 14 | |
| 15 | # Bitwise OR fcntl.LOCK_NB if you need a non-blocking lock |
| 16 | def acquire(self): |
| 17 | fcntl.flock(self.handle, fcntl.LOCK_EX) |
| 18 | |
| 19 | def release(self): |
| 20 | fcntl.flock(self.handle, fcntl.LOCK_UN) |
| 21 | |
| 22 | def __del__(self): |
| 23 | self.handle.close() |