×

go · level 3 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.