🏁 Race Conditions¶
A race condition happens when the correctness of your program depends on timing.
Typical pattern:
- Thread A reads shared state
- Thread B changes it
- Thread A writes back using stale information
Even with the GIL, many multi-step operations ("read-modify-write") are not atomic.
✅ Classic Example: Shared Counter¶
Two threads both run:
That statement is multiple bytecode operations: load, add, store. Another thread can interleave between those steps.
✅ Fixes¶
- Protect the critical section with
threading.Lock - Avoid shared mutable state (message passing,
queue.Queue) - Use higher-level primitives (thread-safe queues, executors)
🔍 Key Takeaways¶
- A race condition is a correctness bug, not just "weird behavior".
- If you share state, you need a strategy: lock, queue, or redesign.