Chapter 0 · Section 1 of 8 · 2 min read

A counter that is sometimes wrong

Imagine a page that shows how many people have visited a website. Every request adds one to a number kept in memory. Two requests arrive at almost the same moment. When both are done, you expect the number to have gone up by two.

Sometimes it goes up by one.

Nothing crashes and nothing is printed. The code is one line long: count++. Your tests pass, because on your laptop two requests rarely land close enough together to collide. The bug waits for a busy day.

This is the bug the whole course is about. It needs only two ingredients:

  • Two pieces of code that run at overlapping times. In Go, these are goroutines.
  • One piece of data that both can change. Here, the counter.

One line is really three steps

count++ looks like a single action. For the computer it is three:

  1. Read the current value of count into a temporary place.
  2. Add one to that temporary copy.
  3. Write the copy back into count.

If one goroutine finishes all three before the other starts, the counter ends at 2. If their steps overlap, this can happen:

MomentGoroutine AGoroutine Bcount in memory
1reads 00
2reads 00
3adds one, writes 11
4adds one, writes 11

Both goroutines did their job, and the counter says 1. B was working from a copy that was already out of date when it wrote. One update is lost.

What this chapter gives you

By the end of the chapter you will be able to:

  • explain, step by step, how two goroutines can lose an update;
  • say how many different orders two small goroutines can run in, and why testing cannot try them all;
  • define a data race using the Go documentation's words;
  • run Go's race detector and read its report;
  • say how Go, C++, Python and Rust each treat this exact bug.

The next section lets you break it yourself.