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 | |
Kate Stone | b9c1b51 | 2016-09-06 20:57:50 +0000 | [diff] [blame] | 8 | |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 9 | class Lock: |
| 10 | |
| 11 | def __init__(self, filename): |
| 12 | self.filename = filename |
| 13 | # This will create it if it does not exist already |
Vince Harron | 85d1965 | 2015-05-21 19:09:29 +0000 | [diff] [blame] | 14 | unbuffered = 0 |
| 15 | self.handle = open(filename, 'a+', unbuffered) |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 16 | |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 17 | def acquire(self): |
| 18 | fcntl.flock(self.handle, fcntl.LOCK_EX) |
| 19 | |
Vince Harron | 85d1965 | 2015-05-21 19:09:29 +0000 | [diff] [blame] | 20 | # will throw IOError if unavailable |
| 21 | def try_acquire(self): |
| 22 | fcntl.flock(self.handle, fcntl.LOCK_NB | fcntl.LOCK_EX) |
| 23 | |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 24 | def release(self): |
| 25 | fcntl.flock(self.handle, fcntl.LOCK_UN) |
| 26 | |
| 27 | def __del__(self): |
| 28 | self.handle.close() |