Go (Golang) Tutorial 0/45 lessons ~6 min read Lesson 26

    Mutex

    Mutex in Module 4 · Concurrency: core concepts, worked examples, and practical guidance in one focused lesson.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    sync.Mutex provides mutual exclusion — only one goroutine holds the lock at a time. RWMutex allows multiple readers or one writer. Use mutexes when goroutines share mutable state: counters, caches, connection pools metadata.

    The race detector (go test -race) finds unsynchronized access — run it in CI. Prefer channels for ownership transfer; use mutexes for protecting shared data structures. sync/atomic offers lock-free counters for simple cases.

    Deadlocks from lock ordering and forgotten Unlock are common production bugs — defer Unlock immediately after Lock.

    The story

    An API gateway maintains an in-memory rate-limit map shared across thousands of goroutines handling concurrent requests. A sync.Mutex protects map writes while sync.RWMutex allows parallel reads during traffic peaks — the same pattern in Cloudflare's edge rate limiters where read-heavy workloads dominate.

    Data races corrupt maps silently; run go test -race in CI to catch missing locks before they become production incidents.

    Understanding the topic

    Key concepts

    • mu.Lock() / mu.Unlock() — exclusive access.
    • RWMutex: RLock/RUnlock for readers; Lock/Unlock for writers.
    • defer mu.Unlock() immediately after Lock — panic-safe.
    • sync/atomic for simple counters without full mutex.
    • Don't copy Mutex — contains internal state; use pointer.
    • Race detector flags unsynchronized concurrent access.

    Step-by-step explanation

    1. Goroutine Lock blocks until mutex available.
    2. Unlock releases; next waiting goroutine proceeds.
    3. RLock allows concurrent readers; Lock blocks all.
    4. Lock while holding Lock same mutex — deadlock.
    5. Zero value Mutex ready to use — no initialization needed.
    6. atomic.AddInt64 for hot-path counters.

    Practical code example

    Thread-safe cache with RWMutex:

    go
    package main
    import (
    "fmt"
    "sync"
    )
    type SafeCache struct {
    mu sync.RWMutex
    items map[string]string
    }
    func NewSafeCache() *SafeCache {
    return &SafeCache{items: make(map[string]string)}
    }
    func (c *SafeCache) Get(key string) (string, bool) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    val, ok := c.items[key]
    return val, ok
    }
    func (c *SafeCache) Set(key, val string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.items[key] = val
    }
    func main() {
    cache := NewSafeCache()
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(n int) {
    defer wg.Done()
    key := fmt.Sprintf("k%d", n%3)
    cache.Set(key, fmt.Sprintf("v%d", n))
    cache.Get(key)
    }(i)
    }
    wg.Wait()
    fmt.Println("cache safe after concurrent access")
    }

    Output

    cache safe after concurrent access

    Line-by-line code explanation

    • type SafeCache struct { bundles a read/write mutex (sync.RWMutex) with a map of string items. The mutex protects the map from being touched by two goroutines at once.
    • return &SafeCache{items: make(map[string]string)} is the constructor. It creates the map with make because writing to a nil map would panic, and it returns a pointer so the mutex is never copied.
    • c.mu.RLock() takes a read lock at the start of Get. Many goroutines can hold a read lock together, and defer c.mu.RUnlock() on the next line releases it when Get returns.
    • val, ok := c.items[key] looks the key up. The ok value says whether the key exists, and both are returned to the caller.
    • c.mu.Lock() takes the exclusive write lock in Set. No other reader or writer can run while it is held, and the deferred Unlock releases it afterwards before c.items[key] = val finishes the method.
    • go func(n int) { starts an anonymous goroutine for each of the ten loop passes. The call ends with }(i), which passes the current i in as n. Each pass also calls wg.Add(1) beforehand.
    • key := fmt.Sprintf("k%d", n%3) builds one of only three keys, k0, k1 or k2. Several goroutines therefore use the same key at the same time, which is why locking matters here.
    • cache.Set(key, fmt.Sprintf("v%d", n)) writes a value for that key, and the following cache.Get(key) reads it back. The result of Get is discarded.
    • fmt.Println("cache safe after concurrent access") runs after wg.Wait() has returned, once all ten goroutines are done.

    Key takeaway: RLock for read-heavy Get; Lock for write Set. defer Unlock prevents leak on panic. Never copy SafeCache struct containing Mutex.

    Real-world use

    Where you'll use this in production

    • In-memory rate limiter and session store.
    • Metrics counter aggregation from many goroutines.
    • Lazy initialization of expensive singleton resources.
    • Protecting map writes in concurrent cache.

    Best practices

    • defer mu.Unlock() immediately after Lock.
    • Hold lock for minimal critical section — no I/O inside lock.
    • Consistent lock ordering across goroutines prevents deadlock.
    • Use RWMutex when reads dominate writes.
    • Run go test -race in CI on every PR.
    • Consider sync.Map for read-heavy cache instead of mutex+map.

    Common mistakes

    • Forgotten Unlock — deadlock.
    • Locking during network call — throughput collapse.
    • Copying struct with embedded Mutex.
    • RWMutex: writer starvation under heavy read load — monitor.
    • Using mutex when channel ownership transfer is clearer.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionMutex vs channel?+

    Answer

    Mutex protects shared state; channel transfers ownership — share memory by communicating.
    2BeginnerQuestionRWMutex when?+

    Answer

    Many concurrent readers, infrequent writers — allows parallel reads.
    3IntermediateQuestionWhy defer Unlock?+

    Answer

    Ensures release on panic or early return — prevents deadlock.
    4IntermediateQuestionDetect data race?+

    Answer

    go test -race; TSAN in CI; review shared mutable state access.
    5AdvancedQuestionDesign concurrent cache with TTL eviction.+

    Answer

    RWMutex + map; background goroutine sweeps; atomic stats; or use ristretto with built-in concurrency.

    Summary

    Mutex serializes access to shared mutable state. RWMutex optimizes read-heavy workloads. Always defer Unlock; keep critical sections small. Run race detector in CI — catches unsynchronized access. Next lesson: context — cancellation and deadlines.

    Ready to mark this lesson complete?Track your journey across the entire course.