Trung BìnhOperating System iconOperating System

Race condition là gì? Cách detect và ngăn chặn trong code thực tế?

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 = 120

Detect: 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:

  1. Mutex/lock bảo vệ critical section;
  2. Atomic operations (sync/atomic Go, java.util.concurrent.atomic);
  3. Immutable data — không thể race nếu không ai write;
  4. Message passing thay vì shared state (Go channels: "Don't communicate by sharing memory, share memory by communicating");
  5. Database-level: optimistic locking (version column) hoặc pessimistic locking (SELECT FOR UPDATE);
  6. CAS (Compare-And-Swap) cho lock-free algorithms

Xem toàn bộ Operating System cùng filter theo level & chủ đề con.

Mở danh sách Operating System