multiple threads able to get flock at the same time

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.

Leave a Comment