8

I have the following code (simplified for clarity):

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)

(Some of the above code is borrowed from this answer.)

When several processes are run at once, this code causes just one to open and write to pyx_file (assuming pyx_file does not already exist). The problem is that as this process is writing to pyx_file, the other processes try to load pyx_file -- errors are raised in the latter processes, because at the time they read pyx_file, it's incomplete. (Specifically, ImportErrors are raised, because the processes are trying to import the contents of the file.)

What's the best way to avoid these errors? One idea is to have the processes keep trying to import pyx_file in a while loop until the import is successful. (This solution seems suboptimal.)

Community
  • 1
  • 1
abcd
  • 10,215
  • 15
  • 51
  • 85

2 Answers2

8

The way to do this is to take an exclusive lock each time you open it. The writer holds the lock while writing data, while the reader blocks until the writer releases the lock with the fdclose call. This will of course fail if the file has been partially written and the writing process exits abnormally, so a suitable error to delete the file should be displayed if the module can't be loaded:

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()
  • 1
    awesome. looks like what i need. one question: is that `with` block necessary? in my code, the "reading" happens in the call to `imp.load_dynamic`. – abcd May 23 '15 at 00:07
  • 1
    Yep. That's the block that waits for the writer to be done writing before trying to load the module. Without that, it'll try to load the module possibly before the writer has finished writing. The lock is the IPC the writer and readers use to communicate that the module is ready. –  May 23 '15 at 00:09
  • That's alright, I've reworked it a bit so that the file will be automatically closed now regardless. I think the fdopen was interfering, but this new edit is safer regardless. –  May 23 '15 at 00:32
  • 1
    OK, i'm trying that out, but are you sure it works? since `fd` is defined outside a `with` block, won't it remain open even when the `with` block for `f` closes? – abcd May 23 '15 at 00:39
  • 2
    Normally it would, but it's getting closed implicitly since we're closing the `file` we've created from it, which closes the underlying `fd` as well. –  May 23 '15 at 00:40
  • Oh yeah, I think you're right. The right thing is to use a lockfile then. Let me update the code. –  May 25 '15 at 00:39
  • I believe `fcntl` only works for unix based systems, so this solution isn't applicable to windows machines. – stackPusher Mar 27 '18 at 16:59
0

Use PID an empty file to lock every time you access a file.

Example usage:

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()

source: Python: module for creating PID-based lockfile?

This will give you a general idea. This method is used in OO, vim and other applications.

Community
  • 1
  • 1
Ahmed
  • 2,825
  • 1
  • 25
  • 39
  • OK, i'll try to modify this to work with my code. since my code is posted in my question, you're welcome to do the same and update your answer correspondingly. – abcd May 22 '15 at 23:53
  • this is also not ideal for me, as my code is from a package that does not have `mercurial` as a dependency. – abcd May 22 '15 at 23:54
  • you can lock it by creating a pid file by using Python IO. – Ahmed May 22 '15 at 23:55
  • i don't want each process to have its own file -- i want all processes to use the same file. would creating a pid file still work for me? – abcd May 22 '15 at 23:56
  • Ok, there is a system call on Linux called flock (f from file), if you're using Linux, you can use it. https://docs.python.org/2/library/fcntl.html – Ahmed May 23 '15 at 00:00
  • the package is meant to work on all OS platforms -- don't want to introduce something Linux-specific. – abcd May 23 '15 at 00:01
  • 1
    @dbliss, all SVR4-compatible UNIXlike systems have either `flock()` or `fcntl(LOCK_*)` or both, and the Python `fcntl.flock()` call will automatically fall back to `fcntl()` if no `flock()` call is available. A UNIX that isn't compatible with SVR4 is unheard of these days -- that's late-80s, to be clear. – Charles Duffy May 23 '15 at 00:34
  • 1
    @dbliss, ...the only platform where you'll have portability problems is Windows, and for that, see http://stackoverflow.com/questions/1422368/fcntl-substitute-on-windows – Charles Duffy May 23 '15 at 00:36
  • @CharlesDuffy cool. do you know what the appropriate calls would be to `win32api`? – abcd May 23 '15 at 00:46
  • I'd start by reading source to the portalocker library referenced by an answer there. I only wear a Windows-developer hat when I'm paid enough to hate myself, and nobody pays me to give StackOverflow advice yet. :) – Charles Duffy May 23 '15 at 00:48