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 |
Vince Harron | 85d1965 | 2015-05-21 19:09:29 +0000 | [diff] [blame^] | 13 | unbuffered = 0 |
| 14 | self.handle = open(filename, 'a+', unbuffered) |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 15 | |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 16 | def acquire(self): |
| 17 | fcntl.flock(self.handle, fcntl.LOCK_EX) |
| 18 | |
Vince Harron | 85d1965 | 2015-05-21 19:09:29 +0000 | [diff] [blame^] | 19 | # will throw IOError if unavailable |
| 20 | def try_acquire(self): |
| 21 | fcntl.flock(self.handle, fcntl.LOCK_NB | fcntl.LOCK_EX) |
| 22 | |
Vince Harron | 05df698 | 2015-05-13 05:00:23 +0000 | [diff] [blame] | 23 | def release(self): |
| 24 | fcntl.flock(self.handle, fcntl.LOCK_UN) |
| 25 | |
| 26 | def __del__(self): |
| 27 | self.handle.close() |