简体   繁体   English

文件锁未按预期工作

[英]File lock not working as expected

I have a Thread -extending class that is supposed to run only one instance at a time (cross-process). 我有一个Thread -extending类,它应该一次只运行一个实例(跨进程)。 In order to achieve that, I'm trying to use a file lock. 为了实现这一点,我正在尝试使用文件锁。 Here are bits 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)

  # Stuff omitted

  def run(self):
    logging.info("Starting scan on %s" % self.path)

    # More stuff omitted

    fcntl.lockf(self.lock_file, fcntl.LOCK_UN)

I was expecting the lockf call to throw an exception if a Scanner thread was already running and not initialize the object at all. 如果Scanner线程已经在运行并且根本没有初始化对象,我期望lockf调用抛出异常。 However, I can 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 suggests that two Scanner threads are running at the same time, no exception thrown. 这表明两个Scanner线程同时运行,没有异常抛出。 I'm sure I'm missing something really basic here, but I can't seem to figure out what that is. 我确定我在这里遗漏了一些非常基本的东西,但我似乎无法弄清楚那是什么。 Can anyone help? 有人可以帮忙吗?

Found the solution myself in the end. 最后我自己找到了解决方案。 It was to use fcntl.flock() instead of fcntl.lockf() , with the exact same parameters. 它是使用fcntl.flock()而不是fcntl.lockf() ,使用完全相同的参数。 Not sure why that made a difference. 不知道为什么会有所作为。

You're opening the lock file using r+ which is erasing the previous file and creating a new one. 您正在使用r+打开锁定文件,该文件正在删除上一个文件并创建一个新文件。 Each thread is locking a different file. 每个线程都锁定一个不同的文件。

Use w or r+a 使用wr+a

Along with using flock, I had to also open the file like so : 除了使用flock,我还必须像这样打开文件:

fd = os.open(lockfile, os.O_CREAT | os.O_TRUNC | os.O_WRONLY)

It does not work other wise. 它没有其他工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM