Understand the contract

A mutex coordinates exclusive access to shared state. Every operation participating in the same invariant must follow the same locking rule. Protect both writes and reads when they can overlap. Waiting for workers to finish is a completion rule; it does not make their overlapping increments safe.

The Counter bundles its mutex with the integer it protects. Add and Value both lock the same mutex. Pointer receivers keep all calls attached to one instance and avoid copying a used mutex. The zero value of sync.Mutex is ready for use; no constructor is required for this counter.

Work through the example

Four workers increment one hundred times each, then main waits and prints 400. The lock covers only the state update. The WaitGroup establishes when all work is finished, while the mutex protects increments during execution. Both mechanisms are necessary for their respective responsibilities.

package main

import (
    "fmt"
    "sync"
)

type Counter struct { mu sync.Mutex; n int }
func (c *Counter) Add() { c.mu.Lock(); c.n++; c.mu.Unlock() }
func (c *Counter) Value() int { c.mu.Lock(); defer c.mu.Unlock(); return c.n }

func main() {
    var counter Counter
    var wg sync.WaitGroup
    for i := 0; i < 4; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := 0; j < 100; j++ { counter.Add() }
        }()
    }
    wg.Wait()
    fmt.Println(counter.Value())
}

Watch this boundary

Do not hold a mutex across slow network operations unless the invariant explicitly requires it. Recursive locking of an ordinary Mutex deadlocks. Keep lock ordering consistent when several locks are necessary, and expose methods instead of returning mutable references to the protected fields.

Practice with a changed input

Run the example with the race detector on a supported toolchain. Add a Reset method using the same mutex, then reason about whether resetting while workers run has useful semantics.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services