Race conditions and interleavings
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.
A sleep made the counter test pass
Your service's hit counter comes up a few short under load. You ask the agent to fix the flaky test that checks it. It adds `time.sleep(0.01)` between thread starts, reruns, gets green and reports "fixed a timing issue". The way the counter is updated did not change.
Is the bug gone, or is it only harder to see?
Steps interleave in orders you didn't pick
Threads run as an **interleaving**: the scheduler can mix each thread's steps in any order. `count += 1` is really three steps: read, add, write. If two threads both read 41, both write 42, and one increment is lost.
Most interleavings are harmless, so tests usually pass. The agent sees one green run and treats it as success. **Later cost:** counts, balances or stock levels silently wrong under real load.
Two shapes, two kinds of race
Look for shared state in two shapes:
- **Read-modify-write**: read, compute, write back (`+=`, append, update a field).
- **Check-then-act**: decide on a check, then act. The fact can change in between.
**Data race**: two threads access the same memory, at least one writes, and nothing synchronizes them. **Logical race**: each access is synchronized, but the multi-step sequence is not. Only synchronization creates ordering: locks, atomics, channels and tools built on them, such as Go's `sync.WaitGroup`. A sleep just makes one order likely.
"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.
Every access locked, still a race
Each map access holds the lock, so `go test -race` stays quiet: there is no data race. But the check (`ok`) and the act (the store) are in separate critical sections. Two goroutines can both miss, both `dial`, and the second store overwrites the first. **Later cost:** on every collision, one caller keeps a connection the cache no longer tracks, so nothing ever closes it. BETTER: one critical section covers both the check and the store (simple, but other callers wait during the dial), or a per-key `sync.Once` makes sure only one caller dials.
// Go
func (c *Cache) Get(k string) *Conn {
c.mu.Lock()
v, ok := c.m[k]
c.mu.Unlock()
if !ok {
v = dial(k)
c.mu.Lock()
c.m[k] = v
c.mu.Unlock()
}
return v
}
Order comes only from synchronization
Concurrent steps can interleave in any order, and a green run shows only one of those orders. Find read-modify-write and check-then-act on shared state. Fix them with a lock, an atomic or a channel that covers the **whole** sequence, never with a sleep. Locking every single access prevents data races, but not logical races.
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.