Chapter 0 · Section 2 of 8 · 3 min read

Break it

Below is a simulator. Each goroutine adds one to the same counter. Every increment is split into the three steps you saw: read, add 1, write. At each step the simulator picks one goroutine at random and lets it do its next step. The random choices come from a seed, so the same seed always plays out the same way. The Switching slider sets how likely the simulator is to move to a different goroutine at each step instead of letting the same one carry on.

This animation needs JavaScript. Here is a text version of one run.

  1. Start: counter = 0. 3 goroutines, 2 increments each.
  2. G3 reads the counter: 0.
  3. G2 reads the counter: 0.
  4. G3 adds one: its copy is now 1.
  5. G2 adds one: its copy is now 1.
  6. G1 reads the counter: 0.
  7. G1 adds one: its copy is now 1.
  8. G1 writes 1.
  9. G1 reads the counter: 1.
  10. G3 writes 1, but the counter was already 1. 1 update is lost.
  11. G3 reads the counter: 1.
  12. G3 adds one: its copy is now 2.
  13. G3 writes 2. G3 is finished.
  14. G2 writes 1, but the counter was already 2. 2 updates are lost.
  15. G2 reads the counter: 1.
  16. G2 adds one: its copy is now 2.
  17. G2 writes 2. G2 is finished.
  18. G1 adds one: its copy is now 2.
  19. G1 writes 2, but the counter was already 2. 1 update is lost. G1 is finished.

Final counter: 2. Expected: 6. 4 updates were lost.

Three goroutines each add one to a shared counter twice. Press Play, or use Step to move one step at a time. The counter should end at 6.

What you should have noticed

  • The goroutines never do anything wrong on their own. Each one reads, adds and writes correctly. The error comes from how their steps interleave.
  • Whether you see the bug depends on timing. With three goroutines adding twice each, I counted seeds 1 to 1000: at 5% switching, 778 runs ended correct; at 50%, only 51; at 80%, none. The code is identical in all three. This is why a bug like this can pass every test on a quiet machine and fail in production.
  • A lucky run proves nothing about the code.
  • Pausing a goroutine between its read and its write makes things worse. In real programs a goroutine can be paused at any moment, by the scheduler, a page fault or a busy machine, and you do not control when.
  • With the mutex on, the final number is right for every seed. It also makes goroutines wait for each other, which you can see when you pause the one holding it.

A text version of every run is available under the animation, for reading with a screen reader or with the animation turned off.