Go Channels vs Mutexes: One Data Race, Two Fixes
- Published
- Duration
- Language
- English
Transcript
Text of the video's narration.
I sent a thousand gophers to add one to a counter. They came back with six hundred seventy-five. Each gopher is a goroutine running count plus plus, and a WaitGroup waits for everyone to wave goodbye. Looks fine. But two of them can read the same number at the same moment, both write back plus one, and one update just vanishes.
Run it with the race flag and Go blows the whistle: data race, a read and a write on the same line. Run it again and you get a different wrong answer. Fix number one: sync.Mutex. Lock the door, one gopher at a time, unlock. Clean, and exactly a thousand.
Fix number two: share memory by communicating. One boss gopher owns the counter, and everyone else passes it notes through a channel. Also clean, also a thousand. So which one? The Go wiki is refreshingly honest: use whichever is most expressive and most simple.
For one counter, the boring padlock usually wins. And whatever you pick, run your tests with the race flag.
Credits and notes
- The Go gopher was designed by Renée French. Licensed under CC BY 4.0. go.dev/blog/gopher
- Changes: poses (rotation, mirroring, squash), props and effects added; no recolour. Source file: gophercolor.png from the official Go website repo (github.com/golang/website, _content/doc/gopher).
- Music: original lofi bed generated in code (royalty-free, see LICENSE-music.md).
- Narrated with Phonon; motion in Remotion.



