Chapter 0 · Section 8 of 8 · 2 min read
Check yourself
Questions
Answer before opening the answer.
- Two goroutines each run read, add, write on one counter. How many interleavings are there, and how many lose an update?
Answer
20 interleavings. 18 lose an update. Only the two orders where one goroutine finishes before the other starts do not. You can reproduce this with node chapters/00-why-concurrency-is-hard/code/interleavings.mjs.
- In your own words, what is a data race? Which three parts of the Go documentation's definition must all hold?
Answer
Two goroutines access the same variable concurrently, and at least one of the accesses is a write. All three must hold: two goroutines, the same variable (with nothing ordering the accesses), and at least one write.
- A test passes ten times in a row. Does that show the code has no data race? What would make a better test?
Answer
No. A race depends on timing, so a quiet machine can hide it. Run the tests with -race, which reports unordered accesses even when the answer happened to be right.
- Why does the file <code>lost_test.go</code> in this chapter's code carry the build tag <code>!race</code>?
Answer
It asserts that the plain counter loses updates. Under -race the detector would report the race and fail the test for a different reason, so the file is left out of race builds.
- Name the three ways out of the shared-data problem from "The idea".
Answer
Do not share; share but never change; share and coordinate.
Exercise
- In the simulator on the Break it page, find a seed and a Switching value where three goroutines adding twice each end at exactly 6 with no mutex. Write the seed down. Now raise Switching to 80%. What happens with the same seed?
- Run
go test -count=1 -v -run Loses ./chapters/00-why-concurrency-is-hard/codethree times. Do the lost counts match each other? Why or why not? - Run
go test -race -tags raceDemo ./chapters/00-why-concurrency-is-hard/codeand find, in the report, the line that read the counter and the line that wrote it. - Change
AtomicCounterto use a plainintand re-run the race detector. What does it report?
What comes next
Chapter 1 gives you the standard tool for this problem when the code you must protect is more than a single number: the mutex. It shows what one is, reads the real Go implementation, and compares it with how Linux, Java, C++, Rust and Python do it.