8

我有以下代码(为清楚起见进行了简化):

import os
import errno
import imp


lib_dir = os.path.expanduser('~/.brian/cython_extensions')
module_name = '_cython_magic_5'
module_path = os.path.join(lib_dir, module_name + '.so')
code = 'some code'

have_module = os.path.isfile(module_path)
if not have_module:
    pyx_file = os.path.join(lib_dir, module_name + '.pyx')

    # THIS IS WHERE EACH PROCESS TRIES TO WRITE TO THE FILE.  THE CODE HERE 
    # PREVENTS A RACE CONDITION.
    try:
        fd = os.open(pyx_file, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass
        else:
            raise
    else:
        os.fdopen(fd, 'w').write(code)

# THIS IS WHERE EACH PROCESS TRIES TO READ FROM THE FILE.  CURRENTLY THERE IS A
# RACE CONDITION.
module = imp.load_dynamic(module_name, module_path)

(上面的一些代码是从这个答案中借来的。)

当同时运行多个进程时,此代码仅导致一个打开和写入pyx_file(假设pyx_file不存在)。问题是,当这个进程正在写入时pyx_file,其他进程会尝试加载pyx_file——在后面的进程中会引发错误,因为在它们读取pyx_file时,它是不完整的。(具体来说,ImportErrors 被提出,因为进程正在尝试导入文件的内容。)

避免这些错误的最佳方法是什么?一个想法是让进程在一个while循环中不断尝试导入pyx_file,直到导入成功。(这个解决方案似乎不是最理想的。)

4

2 回答 2

8

做到这一点的方法是每次打开它时都获取一个独占锁。写入器在写入数据时持有锁,而读取器阻塞,直到写入器通过 fdclose 调用释放锁。如果文件被部分写入并且写入过程异常退出,这当然会失败,因此如果无法加载模块,则应显示删除文件的适当错误:

import os
import fcntl as F

def load_module():
    pyx_file = os.path.join(lib_dir, module_name + '.pyx')

    try:
        # Try and create/open the file only if it doesn't exist.
        fd = os.open(pyx_file, os.O_CREAT | os.O_EXCL | os.O_WRONLY):

        # Lock the file exclusively to notify other processes we're writing still.
        F.flock(fd, F.LOCK_EX)
        with os.fdopen(fd, 'w') as f:
            f.write(code)

    except OSError as e:
        # If the error wasn't EEXIST we should raise it.
        if e.errno != errno.EEXIST:
            raise

    # The file existed, so let's open it for reading and then try and
    # lock it. This will block on the LOCK_EX above if it's held by
    # the writing process.
    with file(pyx_file, "r") as f:
        F.flock(f, F.LOCK_EX)

    return imp.load_dynamic(module_name, module_path)

module = load_module()
于 2015-05-23T00:00:12.787 回答
0

每次访问文件时,使用PID锁定一个空文件。

示例用法:

from mercurial import error, lock

try:
    l = lock.lock("/tmp/{0}.lock".format(FILENAME), timeout=600) # wait at most 10 minutes
    # do something
except error.LockHeld:
     # couldn't take the lock
else:
    l.release()

来源:Python:用于创建基于 PID 的锁定文件的模块?

这会给你一个大致的想法。此方法用于 OO、vim 和其他应用程序。

于 2015-05-22T23:50:09.800 回答