blob: 89823b88abc58801dd8858e725fbe032be976587 [file] [log] [blame]
Vince Harron05df6982015-05-13 05:00:23 +00001"""
2Interprocess mutex based on file locks
3"""
4
5import fcntl
6import os
7
8class Lock:
9
10 def __init__(self, filename):
11 self.filename = filename
12 # This will create it if it does not exist already
Vince Harron85d19652015-05-21 19:09:29 +000013 unbuffered = 0
14 self.handle = open(filename, 'a+', unbuffered)
Vince Harron05df6982015-05-13 05:00:23 +000015
Vince Harron05df6982015-05-13 05:00:23 +000016 def acquire(self):
17 fcntl.flock(self.handle, fcntl.LOCK_EX)
18
Vince Harron85d19652015-05-21 19:09:29 +000019 # will throw IOError if unavailable
20 def try_acquire(self):
21 fcntl.flock(self.handle, fcntl.LOCK_NB | fcntl.LOCK_EX)
22
Vince Harron05df6982015-05-13 05:00:23 +000023 def release(self):
24 fcntl.flock(self.handle, fcntl.LOCK_UN)
25
26 def __del__(self):
27 self.handle.close()