tox-dev/filelock

Why can I acquire the same lock twice?

fostiropoulos opened this issue · 2 comments

It is not clear why I can acquire the same lock more than once e.g.

from filelock import Timeout, FileLock

file_path = "high_ground.txt"
lock_path = "high_ground.txt.lock"

lock = FileLock(lock_path, timeout=1)
lock.acquire()
lock.acquire()

Shouldn't this throw an error?

I did provide a fix in https://github.com/fostiropoulos/py-filelock but based on the other tests it seems like this is a supported use-case but it is unclear from the documentation how to correctly "lock" a file or what is the correct use-case of this library.

asqui commented

The reason that you can acquire the lock multiple times (within the same thread) like this is because FileLocks are reentrant, meaning that if you already hold the lock in a given thread, you can acquire it a second time in the same thread.

If you execute this code snippet in a second thread, or process (e.g. just run a second instance of your code snippet in a separate python interpreter) you'll see that the lock.acquire() will block.

See the last example at https://py-filelock.readthedocs.io/en/latest/#tutorial which illustrates this behaviour, and the Python standard library documentation for RLock for an explanation of reentrant locks: https://docs.python.org/3/library/threading.html#rlock-objects