When multiple goroutines need to read and write the same value, you need a mutex to make sure
they don’t step on each other. Without one, concurrent writes can corrupt the state - two
goroutines might read the same value, both modify it, and one silently overwrites the other’s
change. The usual approach is to put a sync.Mutex next to the fields it protects:
var (
mu sync.Mutex
counter int
)
mu.Lock()
counter++
mu.Unlock()
This works, but nothing enforces it. The compiler won’t stop you from accessing counter
without holding the lock. Forget to lock in one spot and you have a data race. One way to
make this safer is to bundle the value and its mutex into a small generic wrapper that only
exposes locked access through methods: