multiple threads able to get flock at the same time

后端 未结 2 682
梦如初夏
梦如初夏 2020-12-03 21:35

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

2条回答
  •  眼角桃花
    2020-12-03 22:35

    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.

提交回复
热议问题