Fast Thread- and multiprocess-safe file operations in python under Linux
Are there any issues with the code that I should be aware of? (besides from what I already said)
  


If you haven't, maybe read
Everything you never wanted to know about file locking;
I guess the takeaway is that you should make sure that you're actually
getting what you want with the Python fcntl module.

The code looks good to me in general, apart from the bad error handling.

When fcntl.flock throws, the file descriptor from os.open isn't
closed.  This is generally bad and can bite you in the future.

You don't have to care about unlocking as that's done then closing the
file descriptor anyway.

And another issue you missed is that the yield has to be wrapped in a
try/catch in order for the cleanup to run,
c.f. contextmanager.

In summary it should look somewhat like this:

@contextmanager
def locked_open(filename, mode=M_READ, blocking=True):
    open_mode, flock_flags, mode_str = MODES[mode]
    flock_flags = flock_flags | BLOCKING_FLAGS[blocking]

    fd = os.open(filename, open_mode)
    try:
        fcntl.flock(fd, flock_flags)
        fileobj = os.fdopen(fd, mode_str)

        try:
            yield fileobj
        finally:
            fileobj.flush()
            os.fdatasync(fd)
    finally:
        os.close(fd)



  
  Are my tests sufficient?
  


You didn't actually test the interaction between multiple threads and
processes.  Since you're only locking a file descriptor once this will
work as it is though.


  
  Any suggestions regarding performance?
  Are there any easier ways to achieve same result?
  


You'd have to measure that, but since you're using this from a single
application only, using in- and shared-memory locks (from
multiprocessing) could be a faster alternative instead of going
through the filesystem.  But it's way more effort on your end with all
three access modes as you wrote them here and with multiple processes
you'd easily run into more failure modes - I doubt it's worth it.
That said, if you can get away with less features for locking, then you could still investigate it.