Lesson 1 · Unit 08
Goroutines
Start work on the side with go, wait for it, and keep shared data safe.
What you practise
go f(), the program that exits too early,sync.WaitGroup, two goroutines and one counter,sync.Mutex
Try a question from this lesson
Pick one
Writing go in front of a call starts it running on the side, and the program moves straight on without waiting. What can you be sure this prints?
func say(s string) {
fmt.Println(s)
}
go say("hello")
fmt.Println("done")Hint
What happens to a program when main reaches its last line?
Correct answer
done; hello may never appear
Why
go does not wait. main prints "done" and ends, and when main ends the whole program ends, whether or not the other call got its turn. Usually "hello" is lost; now and then it sneaks in. Nothing here makes either 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 at the same time as the code that started it. go f() starts one.
It gives you nothing back and nothing waits for it. When main returns, every goroutine is cut off.
So each time you write go, also decide how you will find out 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.
Add(1) before you start a goroutine. Inside it, defer wg.Done() takes one off the counter when the goroutine finishes, on every path. Wait() blocks until the counter is back at zero.
After Wait returns, everything the goroutines did has happened, so it is safe to read their results.
var wg sync.WaitGroup
msg := ""
wg.Add(1) // one goroutine to wait for
go func() {
defer wg.Done() // finished
msg = "hello"
}()
wg.Wait() // until the count is 0
fmt.Println(msg) // helloConcept
A data race
When goroutines share a variable and at least one of them changes it, with nothing to keep them in order, that is a data race. Updates get lost and the result changes from run to run.
A sync.Mutex is a lock. Between mu.Lock() and mu.Unlock() only one goroutine runs at a time; the others queue up.
count := 0
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
count++ // not guarded: a data race
}()
}
wg.Wait()
fmt.Println(count) // 1000? not always9 more exercises in the app
- 1× true or false
- 2× fill the blanks
- 3× type the answer
- 2× multiple choice
- 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.