0Pricing
Go Academy · Lesson

sync.Mutex and sync.RWMutex

Locking and read-write locking patterns

Why mutexes?

When multiple goroutines share mutable state, concurrent reads and writes cause data races. A mutex serialises access so only one goroutine enters the critical section at a time.

sync.Mutex basics

Lock before reading/writing shared state; Unlock after. Use defer to guarantee unlocking even if the function panics.

var mu sync.Mutex
var counter int

func inc() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}

All lessons in this course

  1. sync.Mutex and sync.RWMutex
  2. sync.WaitGroup
  3. sync.Once and sync.Map
  4. Race Detector and Safe Patterns
← Back to Go Academy