Work effectively with AI coding agents. Understand them as language models running in a tool loop with limited context, which is why they guess, game the visible signal and report confidently. Recognise the shortcut and correctness tells in their code across Python, TypeScript/JavaScript, Rust, Java and Go, and know the damage each one does later. Verify changes instead of trusting them, review diffs fast for quality and security, judge when work is truly finished, and choose, design and steer tasks so agents can finish them well.
Race conditions and interleavings
card 4 of 6
"The GIL makes += safe"
The agent's summary says: "Python's GIL makes `+=` atomic; added a short sleep for the test's timing."
**Tell:** the GIL does not make `+=` atomic. It runs as separate load, add and store steps, and a thread switch can happen between them. Free-threaded Python builds have no GIL at all. **Later cost:** the counter keeps losing hits in production. The sleep only hides this from the test.
**BETTER:** `with lock: count += 1`, using one shared `threading.Lock` that every update takes. The whole read-modify-write then runs as one step that no other thread can split.
Terms on this card
- Read-modify-write
- Reading a shared value, computing a new one from it and writing it back. It is unsafe if another thread can act between the read and the write.
- atomic
- Done as one indivisible step that other threads cannot observe half-done or interrupt. Atomic types (for example atomic integers) provide this for single operations.
- GIL
- Global Interpreter Lock: in standard CPython, only one thread runs Python bytecode at a time. It does not make multi-step operations such as += atomic.
- Free-threaded
- A CPython build (3.13 onward, optional) that runs without the GIL, so Python threads can truly run in parallel.
- threading.Lock
- Python's basic mutual-exclusion lock. Code inside `with lock:` runs in only one thread at a time.
Lesson goal: Explain how concurrent code can interleave and produce wrong results, using check-then-act and read-modify-write as examples. Distinguish a data race from a logical race, and explain why only synchronization (locks, atomics, channels) creates ordering while timing does not. ·
the whole lesson