Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

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.

Info

Even with the race detector, logic bugs (e.g., deadlocks) need careful design.

Previous: WebSockets with `gorilla/websocket`Next: Building a Simple CLI Tool – Argument Parsing