blob: 8bd8b32f4598290208b84a30bc57c8a4e8c9c8e1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
class Lock():
"""Simple implementation of a mutex lock using the file systems. Works on
*nix systems."""
path = None
_has_lock = False
def __init__(self, path):
self.path = path
def obtain(self):
import os
import logging
logger = logging.getLogger()
try:
os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
self._has_lock = True
logger.info("Successfully obtained lock: %s" % self.path)
except OSError:
return False
else:
return True
def release(self):
import os
import logging
logger = logging.getLogger()
if not self._has_lock:
raise Exception("Unable to release lock that is owned by another process")
try:
os.remove(self.path)
logger.info("Successfully released lock: %s" % self.path)
finally:
self._has_lock = False
def has_lock(self):
return self._has_lock
def clear(self):
import os
import logging
logger = logging.getLogger()
try:
os.remove(self.path)
except OSError:
pass
finally:
logger.info("Successfully cleared lock: %s" % self.path)
self._has_lock = False
|