Lesson 39 of 60 · Go
Testing Concurrency – Race Detector and `testing`
Duration: 20 minutes
Testing Concurrent Code
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Race Detector
Run tests with -race to catch data races.
$ go test -race ./...
Example: Concurrent Counter
type Counter struct { n int; mu sync.Mutex }
func (c *Counter) Inc() { c.mu.Lock(); c.n++; c.mu.Unlock() }
func (c *Counter) Value() int { c.mu.Lock(); defer c.mu.Unlock(); return c.n }
func TestCounter(t *testing.T) {
var c Counter
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() { c.Inc(); wg.Done() }()
}
wg.Wait()
if got := c.Value(); got != 1000 { t.Fatalf("got %d, want 1000", got) }
}
The race detector will flag any missing synchronization.