Mutex and Data Race

counter++ is not one action. It is read, add, write, and two goroutines can interleave those steps.

The idea

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.

Watch it work

Try it

Common mistakes