Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
The GIL can switch threads between bytecode instructions, so read-modify-write operations like += or check-then-act sequences are not atomic; protect shared state with locks, use thread-safe queues, or avoid shared mutable state altogether.
An operation such as balance += amount compiles to several bytecode steps: load, add and store. If the interpreter switches threads between them, two threads can read the same old value and one update is lost. The same applies to patterns like if key not in cache: cache[key] = compute(), and to state shared across processes or servers, where the GIL provides no protection at all. Within one process, use threading.Lock around critical sections, queue.Queue to hand work between threads, or designs where each thread owns its data. For shared state across processes or machines, rely on database transactions, row locks, atomic updates like UPDATE ... SET x = x + 1, or distributed locks. Such bugs are timing-dependent, so stress tests and code review matter more than unit tests.