I was under the impression that flock(2) is thread safe, I recently, ran across the case in the code, where multiple threads are able to get a lock on the same file which ar
From the Linux man page for flock(2):
Locks created by flock() are associated with an open file table entry. This means that duplicate file descriptors (created by, for example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using any of these descriptors. Furthermore, the lock is released either by an explicit LOCK_UN operation on any of these duplicate descriptors, or when all such descriptors have been closed.
In addition, flock locks don't 'stack', so if you try to acquire a lock you already hold, the flock call is a noop that returns immediately without blocking and without changing the lock state in any way.
Since threads within a process share file descriptors, you can flock the file multiple times from different threads, and it won't block, as the lock is already held.
Also from the notes on flock(2):
flock() and fcntl(2) locks have different semantics with respect to forked processes and dup(2). On systems that implement flock() using fcntl(2), the semantics of flock() will be different from those described in this manual page.
flock(2) is documented as "blocking if an incompatible lock is held by another process"
and with "locks created by flock() are associated with an open file table entry", so it should be expected that flock
-ed locks by several threads of the same process don't interact.
(the flock
documentation doesn't mention threads).
Hence, the solution should be simple for you: associate one pthread_mutex_t
to every flock
-able file descriptor, and protect the call to flock
with that mutex. You might also use pthread_rwlock_t if you want a read vs write locking.