def __lock(self, *, write: bool=True):
"""
A context manager to lock the storage for reading or writing.
If no processes hold the lock for writing, then several
processes can simultaneously lock the storage for reading.
If a process holds the lock for writing, then no other process
can take the lock (either for reading or writing).
If the lock cannot be obtained, the process is paused until
the situation allows to take it.
Args:
write -- (bool) if False, the storage is locked for
reading. If True, the storage is locked for writing.
"""
assert not self.__locked, 'Nested lock'
if self.__lockable:
flags = fcntl.LOCK_SH if not write else fcntl.LOCK_EX
fcntl.lockf(self.__file, flags, 1)
self.__locked = True
try:
yield
finally:
fcntl.lockf(self.__file, fcntl.LOCK_UN, 1)
self.__locked = False
else:
yield
评论列表
文章目录