multiple threads able to get flock at the same time

后端 未结 2 681
梦如初夏
梦如初夏 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:12

    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.

提交回复
热议问题