Download utils/lazy.py from pswap/phlam: direct link, hf CLI and curl.
- Browser
- Download file 651 Bytes
-
https://huggingface.co/spaces/pswap/phlam/resolve/main/utils/lazy.py
- Command line
-
hf download hf://spaces/pswap/phlam/utils/lazy.py
-
curl -L -o lazy.py https://huggingface.co/spaces/pswap/phlam/resolve/main/utils/lazy.py
651 Bytes
| """Thread-safe lazy singleton: a background warm-up thread and a real | |
| request's first call can both reach a getter before construction finishes | |
| -- without locking they'd race to build two copies of the same model/index | |
| concurrently (wasted memory, and double the load on an already-flaky | |
| network mount). This makes the second caller block and reuse the first's | |
| result instead.""" | |
| import threading | |
| def lazy_singleton(factory): | |
| lock = threading.Lock() | |
| box = {} | |
| def get(): | |
| if "v" not in box: | |
| with lock: | |
| if "v" not in box: | |
| box["v"] = factory() | |
| return box["v"] | |
| return get | |