harlowja / fasteners

A python package that provides useful locks.
Apache License 2.0
243 stars 45 forks source link

How to acquire read lock twice in the same process? #115

Closed Rizhiy closed 1 month ago

Rizhiy commented 1 month ago

Hi, is it possible to acquire read lock twice in the same thread?

Basically, what I want to do is:

from fasteners import InterProcessReaderWriterLock

lock = InterProcessReaderWriterLock("lock.file")

with lock.read_lock():
    with lock.read_lock():
        print("Test")

As I understand, read_lock() is supposed to be non-exclusive. But when I try to run code above, I get:

Traceback (most recent call last):
  File "/home/rizhiy/projects/class-cache/tmp.py", line 5, in <module>
    with lock.read_lock():
  File "/home/rizhiy/miniconda3/envs/class-cache/lib/python3.11/contextlib.py", line 144, in __exit__
    next(self.gen)
  File "/home/rizhiy/miniconda3/envs/class-cache/lib/python3.11/site-packages/fasteners/process_lock.py", line 242, in read_lock
    self.release_read_lock()
  File "/home/rizhiy/miniconda3/envs/class-cache/lib/python3.11/site-packages/fasteners/process_lock.py", line 385, in release_read_lock
    _interprocess_reader_writer_mechanism.unlock(self.lockfile)
  File "/home/rizhiy/miniconda3/envs/class-cache/lib/python3.11/site-packages/fasteners/process_mechanism.py", line 130, in unlock
    fcntl.lockf(lockfile, fcntl.LOCK_UN)
TypeError: argument must be an int, or have a fileno() method.
psarka commented 1 month ago

Unfortunately, InterProcessReaderWriterLock is not "reentrant" (so you can't acquire lock twice) :(

image