go · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Give every goroutine its own slot, then print after Wait.
You can write a function with no name right where you need it: func(n int) { ... }(5) defines it and calls it at once. Inside, it can use nearby variables such as wg and results. A function like that is a . Put go in front and it runs as a goroutine.
Goroutines finish in any order, so never let them print. Give each one its own slot in a slice made with make([]string, len(items)). Each goroutine writes only results[i], nobody shares a slot, and after wg.Wait() main prints them in order. Same output, every run.
Concurrency is not . Concurrency is how you arrange the work; parallelism is several processor cores truly running at once. Go uses every core it can, but your program must give the same answer on one core or on sixty-four.
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
orders := []string{"cake", "tea", "jam"}
results := make([]string, len(orders))
var wg sync.WaitGroup
for i, order := range orders {
wg.Add(1)
go func(i int, order string) {
defer wg.Done()
results[i] = strings.ToUpper(order)
}(i, order)
}
wg.Wait()
fmt.Println(results)
} defer wg.Done() on the first line counts the goroutine off however its function ends.
guess first
Three goroutines, three slots. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import (
"fmt"
"sync"
)
func main() {
scores := []int{3, 5, 2}
doubled := make([]int, len(scores))
var wg sync.WaitGroup
for i, s := range scores {
wg.Add(1)
go func(i, s int) {
defer wg.Done()
doubled[i] = s * 2
}(i, s)
}
wg.Wait()
fmt.Println(doubled)
}
your turn
Your turn. Greet every pet at once.
Name three pets, real or made up. Then fill the slot each goroutine writes to and the method that waits for all of them.
output
press run to see what happens
fix it
The slots are missing. Can you fix it?
output
press run to see what happens
- Read the panic: the index is out of range. Slot
idoes not exist yet. make([]int, 0, len(fruit))gives a slice of length 0 with room to grow. Each goroutine needs its slot to exist already.- Change it to
make([]int, len(fruit))so all three slots exist before any goroutine starts.
nailed it
every goroutine filled its own slot. :D
- A closure is a function that uses variables from around it.
defer wg.Done()counts a goroutine off however it ends.- Own slots plus
Waitgive the same output every run.
new words in your collection
- closure
- parallelism
This lesson isn’t saved. A free account remembers every lesson you finish.