I have a Thread-extending class that should only run one instance at a time (cross process). For this I am trying to use file locking. Here are the snippets of my code:
class Scanner(Thread):
def __init__(self, path):
Thread.__init__(self)
self.lock_file = open(os.path.join(config.BASEDIR, "scanner.lock"), 'r+')
fcntl.lockf(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
def run(self):
logging.info("Starting scan on %s" % self.path)
fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
I expected the call to lockfthrow an exception if the thread is Scanneralready running, rather than initializing the object at all. However, I see this in the terminal:
INFO:root:Starting scan on /home/felix/Music
INFO:root:Starting scan on /home/felix/Music
INFO:root:Scan finished
INFO:root:Scan finished
Which assumes that two threads Scannerare running at the same time, no exception is thrown. I am sure that I am missing something really basic, but I can’t understand what it is. Can anyone help?
Felix source
share