晋太元中,武陵人捕鱼为业。缘溪行,忘路之远近。忽逢桃花林,夹岸数百步,中无杂树,芳草鲜美,落英缤纷。渔人甚异之,复前行,欲穷其林。 林尽水源,便得一山,山有小口,仿佛若有光。便舍船,从口入。初极狭,才通人。复行数十步,豁然开朗。土地平旷,屋舍俨然,有良田、美池、桑竹之属。阡陌交通,鸡犬相闻。其中往来种作,男女衣着,悉如外人。黄发垂髫,并怡然自乐。 见渔人,乃大惊,问所从来。具答之。便要还家,设酒杀鸡作食。村中闻有此人,咸来问讯。自云先世避秦时乱,率妻子邑人来此绝境,不复出焉,遂与外人间隔。问今是何世,乃不知有汉,无论魏晋。此人一一为具言所闻,皆叹惋。余人各复延至其家,皆出酒食。停数日,辞去。此中人语云:“不足为外人道也。”(间隔 一作:隔绝) 既出,得其船,便扶向路,处处志之。及郡下,诣太守,说如此。太守即遣人随其往,寻向所志,遂迷,不复得路。 南阳刘子骥,高尚士也,闻之,欣然规往。未果,寻病终。后遂无问津者。
| DIR:/opt/hc_python/lib64/python3.12/site-packages/virtualenv/util/ |
| Current File : //opt/hc_python/lib64/python3.12/site-packages/virtualenv/util/lock.py |
"""holds locking functionality that works across processes."""
from __future__ import annotations
import logging
import os
from abc import ABC, abstractmethod
from contextlib import contextmanager, suppress
from pathlib import Path
from threading import Lock, RLock
from filelock import FileLock, Timeout
LOGGER = logging.getLogger(__name__)
class _CountedFileLock(FileLock):
def __init__(self, lock_file) -> None:
parent = os.path.dirname(lock_file)
if not os.path.isdir(parent):
with suppress(OSError):
os.makedirs(parent)
super().__init__(lock_file)
self.count = 0
self.thread_safe = RLock()
def acquire(self, timeout=None, poll_interval=0.05):
if not self.thread_safe.acquire(timeout=-1 if timeout is None else timeout):
raise Timeout(self.lock_file)
if self.count == 0:
super().acquire(timeout, poll_interval)
self.count += 1
def release(self, force=False): # noqa: FBT002
with self.thread_safe:
if self.count > 0:
self.thread_safe.release()
if self.count == 1:
super().release(force=force)
self.count = max(self.count - 1, 0)
_lock_store = {}
_store_lock = Lock()
class PathLockBase(ABC):
def __init__(self, folder) -> None:
path = Path(folder)
self.path = path.resolve() if path.exists() else path
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.path})"
def __truediv__(self, other):
return type(self)(self.path / other)
@abstractmethod
def __enter__(self):
raise NotImplementedError
@abstractmethod
def __exit__(self, exc_type, exc_val, exc_tb):
raise NotImplementedError
@abstractmethod
@contextmanager
def lock_for_key(self, name, no_block=False): # noqa: FBT002
raise NotImplementedError
@abstractmethod
@contextmanager
def non_reentrant_lock_for_key(self, name):
raise NotImplementedError
class ReentrantFileLock(PathLockBase):
def __init__(self, folder) -> None:
super().__init__(folder)
self._lock = None
def _create_lock(self, name=""):
lock_file = str(self.path / f"{name}.lock")
with _store_lock:
if lock_file not in _lock_store:
_lock_store[lock_file] = _CountedFileLock(lock_file)
return _lock_store[lock_file]
@staticmethod
def _del_lock(lock):
if lock is not None:
with _store_lock, lock.thread_safe:
if lock.count == 0:
_lock_store.pop(lock.lock_file, None)
def __del__(self) -> None:
self._del_lock(self._lock)
def __enter__(self):
self._lock = self._create_lock()
self._lock_file(self._lock)
def __exit__(self, exc_type, exc_val, exc_tb):
self._release(self._lock)
self._del_lock(self._lock)
self._lock = None
def _lock_file(self, lock, no_block=False): # noqa: FBT002
# multiple processes might be trying to get a first lock... so we cannot check if this directory exist without
# a lock, but that lock might then become expensive, and it's not clear where that lock should live.
# Instead here we just ignore if we fail to create the directory.
with suppress(OSError):
os.makedirs(str(self.path))
try:
lock.acquire(0.0001)
except Timeout:
if no_block:
raise
LOGGER.debug("lock file %s present, will block until released", lock.lock_file)
lock.release() # release the acquire try from above
lock.acquire()
@staticmethod
def _release(lock):
lock.release()
@contextmanager
def lock_for_key(self, name, no_block=False): # noqa: FBT002
lock = self._create_lock(name)
try:
try:
self._lock_file(lock, no_block)
yield
finally:
self._release(lock)
finally:
self._del_lock(lock)
lock = None
@contextmanager
def non_reentrant_lock_for_key(self, name):
with _CountedFileLock(str(self.path / f"{name}.lock")):
yield
class NoOpFileLock(PathLockBase):
def __enter__(self):
raise NotImplementedError
def __exit__(self, exc_type, exc_val, exc_tb):
raise NotImplementedError
@contextmanager
def lock_for_key(self, name, no_block=False): # noqa: ARG002, FBT002
yield
@contextmanager
def non_reentrant_lock_for_key(self, name): # noqa: ARG002
yield
__all__ = [
"NoOpFileLock",
"ReentrantFileLock",
"Timeout",
]
|