Search RU
Tasks / Concurrency / Race in lazy initialisation
Statement medium

Race in lazy initialisation

`LazyValue` must load its value once, even when `get()` is called from several
threads at the same time. `starter.py` has no lock: every thread passes the
`if self._value is None` check before the first write and calls `loader` every
time.

Fix the class so that:

- `loader` is called exactly once under concurrent `get()` calls;
- all threads receive the same object;
- `None` is a valid cached value, not a "not loaded yet" marker;
- if `loader` raises, the exception propagates and the next `get()` retries the
load;
- `calls` counts real `loader` invocations, not cache hits;
- the API (`LazyValue`, `get()`, `calls`) stays the same;
- the lock is not held during `loader` itself, if that is possible without
losing the single-call guarantee.

The hidden tests start eight threads through a `Barrier` and check the call
count, object identity and the retry after an error.

concurrencylazy-initdouble-checked-lockingrace
solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

Why does `if self._value is None` let eight threads through? And why can't
`None` mark "not loaded yet"?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts