blob: 0e3af4a6b16e3fa001252c83760d4f6184903083 [file] [log] [blame]
Vince Harron05df6982015-05-13 05:00:23 +00001"""
2Interprocess mutex based on file locks
3"""
4
5import fcntl
6import os
7
Kate Stoneb9c1b512016-09-06 20:57:50 +00008
Vince Harron05df6982015-05-13 05:00:23 +00009class Lock:
10
11 def __init__(self, filename):
12 self.filename = filename
13 # This will create it if it does not exist already
Vince Harron85d19652015-05-21 19:09:29 +000014 unbuffered = 0
15 self.handle = open(filename, 'a+', unbuffered)
Vince Harron05df6982015-05-13 05:00:23 +000016
Vince Harron05df6982015-05-13 05:00:23 +000017 def acquire(self):
18 fcntl.flock(self.handle, fcntl.LOCK_EX)
19
Vince Harron85d19652015-05-21 19:09:29 +000020 # will throw IOError if unavailable
21 def try_acquire(self):
22 fcntl.flock(self.handle, fcntl.LOCK_NB | fcntl.LOCK_EX)
23
Vince Harron05df6982015-05-13 05:00:23 +000024 def release(self):
25 fcntl.flock(self.handle, fcntl.LOCK_UN)
26
27 def __del__(self):
28 self.handle.close()