flock locks do not care about threads - in fact, they do not care about processes. If you take the same file descriptor in two processes (inherited via fork), or the file lock process with this FD gets a lock for both processes. In other words, in the following code, both flock calls will return success: the child process locks the file, and then the parent process gets the same lock, not the lock, because they are both the same FD.
import fcntl, time, os f = open("testfile", "w+") print "Locking..." fcntl.flock(f.fileno(), fcntl.LOCK_EX) print "locked" fcntl.flock(f.fileno(), fcntl.LOCK_UN) if os.fork() == 0:
At the same time, if you lock the same file twice, but with different file descriptors, the locks will lock each other - regardless of whether you are in the same process or in the same thread. See Flock (2): If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another descriptor. If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another descriptor.
It is useful to remember that the Linux kernel, processes and threads are essentially the same thing, and they are usually handled by the same kernel-level APIs. For the most part, if syscall documents handle child / parent behavior, they will be preserved for streams.
Of course, you can (and probably should) test this behavior yourself.
source share