| 9 | logger = build_logger() |
| 10 | |
| 11 | class ThreadSafeObject: |
| 12 | def __init__( |
| 13 | self, key: Union[str, Tuple], obj: Any = None, pool: "CachePool" = None |
| 14 | ): |
| 15 | self._obj = obj |
| 16 | self._key = key |
| 17 | self._pool = pool |
| 18 | self._lock = threading.RLock() |
| 19 | self._loaded = threading.Event() |
| 20 | |
| 21 | def __repr__(self) -> str: |
| 22 | cls = type(self).__name__ |
| 23 | return f"<{cls}: key: {self.key}, obj: {self._obj}>" |
| 24 | |
| 25 | @property |
| 26 | def key(self): |
| 27 | return self._key |
| 28 | |
| 29 | @contextmanager |
| 30 | def acquire(self, owner: str = "", msg: str = "") -> Generator[None, None, FAISS]: |
| 31 | owner = owner or f"thread {threading.get_native_id()}" |
| 32 | try: |
| 33 | self._lock.acquire() |
| 34 | if self._pool is not None: |
| 35 | self._pool._cache.move_to_end(self.key) |
| 36 | logger.info(f"{owner} 开始操作:{self.key}。{msg}") |
| 37 | yield self._obj |
| 38 | finally: |
| 39 | logger.info(f"{owner} 结束操作:{self.key}。{msg}") |
| 40 | self._lock.release() |
| 41 | |
| 42 | def start_loading(self): |
| 43 | self._loaded.clear() |
| 44 | |
| 45 | def finish_loading(self): |
| 46 | self._loaded.set() |
| 47 | |
| 48 | def wait_for_loading(self): |
| 49 | self._loaded.wait() |
| 50 | |
| 51 | @property |
| 52 | def obj(self): |
| 53 | return self._obj |
| 54 | |
| 55 | @obj.setter |
| 56 | def obj(self, val: Any): |
| 57 | self._obj = val |
| 58 | |
| 59 | |
| 60 | class CachePool: |
nothing calls this directly
no outgoing calls
no test coverage detected