go · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put go in front of a call and it runs alongside main.
So far your programs did one thing at a time, top to bottom. Write the keyword go in front of a function call and Go starts it as a : a separate strand of work running alongside everything else. Juggling several jobs in overlapping time like this is called .
main is a goroutine too, and when it returns the whole program stops, even if other goroutines are halfway through. So main has to wait. A is a counter for that: Add(1) before starting, Done() when the work is finished, Wait() to pause until the count is zero.
Hand the goroutine a pointer, &wg, so both sides share one counter instead of two separate copies.
package main
import (
"fmt"
"sync"
)
func bake(wg *sync.WaitGroup) {
fmt.Println("Baking the bread...")
wg.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go bake(&wg)
wg.Wait()
fmt.Println("Dinner is ready!")
} Without wg.Wait(), main could finish before the bread is baked, and you might never see that line.
guess first
The kettle boils in a goroutine. What does main see?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import (
"fmt"
"sync"
)
func boil(kettle *string, wg *sync.WaitGroup) {
*kettle = "boiled"
wg.Done()
}
func main() {
var wg sync.WaitGroup
kettle := "cold"
wg.Add(1)
go boil(&kettle, &wg)
wg.Wait()
fmt.Println("The kettle is", kettle)
}
your turn
Your turn. Pack a bag in a goroutine.
Fill the three blanks: how many goroutines main waits for, something to pack, and the method that makes main wait. Then run it.
output
press run to see what happens
fix it
This trip never sets off. Can you fix it?
output
press run to see what happens
- Read the error: all goroutines are asleep.
mainis waiting for something that never comes. - Count the goroutines started with
go, then compare that with the number given towg.Add. - There is one goroutine, so change
wg.Add(2)towg.Add(1).
nailed it
your code can do two things at once. :D
goin front of a call starts a goroutine.- When
mainreturns, every other goroutine stops with it. Add,DoneandWaiton a WaitGroup makemainwait.
new words in your collection
- goroutine
- concurrency
- WaitGroup
This lesson isn’t saved. A free account remembers every lesson you finish.