phlam / utils /lazy.py
pswap's picture
duckdb threadsafe
4b63894
Raw History Blame Contribute Delete
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