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
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.