Lesson 1 · Unit 03
Goroutines
Start work with go, wait with a WaitGroup, guard data with a Mutex.
What you practise
go f(), the program that exits too early,sync.WaitGroup, a data race andsync.Mutex
Try a question from this lesson
Pick one
Putting go in front of a call starts it running on the side and moves straight on. What can you say for certain about this program's output?
func say(s string) {
fmt.Println(s)
}
go say("hello")
fmt.Println("done")Correct answer
done prints; hello may never appear
Why
go does not wait. main prints "done" and returns, and when main returns the program ends, whether or not the other goroutine got its turn. Usually "hello" is lost; sometimes it sneaks in first. Nothing here makes either order certain.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Goroutines
A goroutine is a function call that runs concurrently with the code that started it. They are far cheaper than operating system threads: the Go runtime spreads thousands of them over a few threads.
go f() gives you no handle and no return value, and nothing waits for it. When main returns, every goroutine is cut off. So each time you write go you must also decide how you will learn that the work is done.
func say(s string) {
fmt.Println(s)
}
go say("hello") // starts, does not wait
go func() { // a function literal
fmt.Println("hi")
}() // called on the spotConcept
Waiting with a WaitGroup
A sync.WaitGroup is a counter you can wait on. Call Add(1) before starting each goroutine, have the goroutine call Done() when it finishes (with defer, so it happens on every path), and call Wait() where you need the results: it blocks until the counter is back to zero.
Wait also makes it safe to read what the goroutines wrote: everything they did happened before it returned.
var wg sync.WaitGroup
msg := ""
wg.Add(1) // one goroutine to wait for
go func() {
defer wg.Done() // it has finished
msg = "hello"
}()
wg.Wait() // blocks until the count is 0
fmt.Println(msg) // helloConcept
A data race, and a lock
When two goroutines use the same variable, at least one of them writes, and nothing orders them, that is a data race. The result is not merely "a little off": the language makes no promise about it at all.
A sync.Mutex fixes it. Between Lock and Unlock only one goroutine runs; the others queue up. Running a program or its tests with the -race flag reports races as they happen.
counter := 0
var wg sync.WaitGroup
for range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // unguarded: a data race
}()
}
wg.Wait()
fmt.Println(counter) // 1000? not always9 more exercises in the app
- 2× true or false
- 2× fill the blanks
- 2× multiple choice
- 2× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.