Trung BìnhGolang iconGolang

go test -race là gì? Khi nào nên chạy?

Race detector (-race flag) là công cụ tích hợp trong Go runtime, phát hiện data race — khi hai goroutines truy cập cùng vùng nhớ đồng thời mà không sync, ít nhất một thao tác là write.

Race detector hoạt động bằng cách instrument binary tại compile time, theo dõi mọi memory access.

bash
# Chạy tests với race detector
go test -race ./...

# Chạy binary với race detector
go run -race main.go
go build -race -o app && ./app

# Output khi phát hiện race
WARNING: DATA RACE
Write at 0x00c0000b4010 by goroutine 7:
  main.increment()
      /app/main.go:12
Read at 0x00c0000b4010 by goroutine 8:
  main.readValue()
      /app/main.go:18

Overhead: ~5-10x chậm hơn và dùng nhiều memory hơn — không dùng trong production binary.

Best practice: luôn chạy -race trong CI pipeline. Với service high-load, có thể enable race detector trên 1 instance staging riêng để phát hiện race conditions khó reproduce.

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

Mở danh sách Golang