counter++ is not one action. It is read, add, write, and two goroutines can interleave those steps.
Two people share a whiteboard with the number 0. Each one does “read the number, add 1 in my head, write the answer back”. If both read 0 before either writes, both write 1, and one increment is lost. The board says 1, not 2.
That is a data race: two goroutines touch the same variable at the same time and at least one writes. A mutex (mutual exclusion lock) is a pen only one person can hold: take it (Lock), do the whole read-add-write, give it back (Unlock). Nobody else can start until it is free.
1 1 1 2 2 2 (no overlap) and then 1 2 2 1 1 2. Which orders lose an update?go run -race . to see Go report the race for you.counter++ is atomic. It is not; use a sync.Mutex or sync/atomic.Unlock (use defer mu.Unlock() right after Lock), which freezes every other goroutine.go test -race ./...; the race detector prints WARNING: DATA RACE.