Code Room
Code reviewMediumcr-g230
Subject Atomicity violationsLevel Mid–Senior~25 minCommon in Concurrency interviewsIndustries Software development

Question

Review this Python deduplicating cache populated by multiple threads.

The write is locked — is this correct under threads?

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix — specific and kind.

Talk through your review
Code to reviewpython
import threading class Memo:    def __init__(self):        self._cache = {}        self._lock = threading.Lock()     def get(self, key, compute):        if key not in self._cache:        # (1) check            value = compute(key)          # (2) expensive, no lock            with self._lock:                self._cache[key] = value  # (3) store under lock        return self._cache[key]           # (4)
Run or narrate your approach, then ask the coach.