views:

53

answers:

1

I have a question about how flock() works, particularly in python. I have a module that opens a serial connection (via os.open()). I need to make this thread safe. It's easy enough making it thread safe when working in the same module using threading.Lock(), but if the module gets imported from different places, it breaks.

I was thinking of using flock(), but I'm having trouble finding enough information about how exactly flock works. I read that flock() unlocks the file once the file is closed. But is there a situation that will keep the file open if python crashes?

And what exactly is allowed to use the locked file if LOCK_EX is set? Just the module that locked the file? Any module that was imported from the script that was originally run?

+1  A: 

When a process dies the OS should clean up any open file resources (with some caveats, I'm sure). This is because the advisory lock is released when the file is closed, an operation which occurs as part of the OS cleanup when the process exits.

Remember flock(2) is just advisory. You can't flock(2) the same file twice with LOCK_EX, but you can "lock" it any number of times with LOCK_SH (as long as there is no LOCK_EX on it, etc.). YMMV on a "non-UNIX" system or a non-local filesystem.

flock works at the OS/process level and is independent of python modules. One module may request n locks, or n locks could be requested across m modules.

pst
In other words, ANYONE can use a file which had been flocked even with `LOCK_EX`. However, no one else will be able to obtain a lock.
Michael Mior