Race condition xảy ra khi kết quả của chương trình phụ thuộc vào thứ tự/timing của các concurrent operations — thứ tự không được control → kết quả unpredictable. Ví dụ kinh điển (balance):
text
Thread 1: read balance=100, Thread 2: read balance=100
Thread 1: balance += 50 → 150, Thread 2: balance -= 30 → 70
Thread 1: write 150, Thread 2: write 70 (lost update!)
Expected: 100 + 50 - 30 = 120Detect: Go race detector (go test -race, go run -race); Java ThreadSanitizer; Helgrind (Valgrind tool); code review tìm shared mutable state không có synchronization. Ngăn chặn:
- Mutex/lock bảo vệ critical section;
- Atomic operations (
sync/atomicGo,java.util.concurrent.atomic); - Immutable data — không thể race nếu không ai write;
- Message passing thay vì shared state (Go channels: "Don't communicate by sharing memory, share memory by communicating");
- Database-level: optimistic locking (version column) hoặc pessimistic locking (SELECT FOR UPDATE);
- CAS (Compare-And-Swap) cho lock-free algorithms