如何在多个进程尝试写入然后同时从文件读取时防止竞争条件

dbl*_*iss 5 python io race-condition python-import python-os

我有以下代码(为简洁起见而简化):

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)
Run Code Online (Sandbox Code Playgroud)

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

当一次运行多个进程时,此代码只会导致一个进程打开并写入pyx_file(假设pyx_file尚不存在).问题在于,当这个过程正在写入时pyx_file,其他进程会尝试加载pyx_file- 在后面的进程中会出现错误,因为在他们阅读时pyx_file,它是不完整的.(具体来说,ImportError会引发s,因为进程正在尝试导入文件的内容.)

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

小智 7

执行此操作的方法是每次打开时都使用独占锁.编写器在写入数据时保持锁定,而读取器阻塞,直到编写器使用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()
Run Code Online (Sandbox Code Playgroud)

  • 通常它会,但它会被隐式关闭,因为我们正在关闭我们从它创建的`file`,这也关闭了底层的`fd`. (2认同)