×

go · level 3 · unit 4 · lesson 4

  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

Let one goroutine own the data, and send it requests.

A Go proverb says: do not communicate by sharing memory; share memory by communicating. Instead of many goroutines locking one map, hand the map to a single goroutine. Nobody else touches it, ever. Keeping data inside one goroutine like this is called .

Others send that owner requests on a channel. A request that needs an answer carries its own : the owner does the work and sends the result back on it. Only the owner touches the data, so there is nothing to lock and nothing to race.

A mutex is fine for small shared state. An owner shines when the state has rules, or many steps that must happen in order.

package main
import "fmt"
type order struct {
	item  string
	reply chan int
}
func keeper(orders chan order) {
	stock := map[string]int{"apples": 5, "pears": 2}
	for o := range orders {
		stock[o.item]--
		o.reply <- stock[o.item]
	}
}
func main() {
	orders := make(chan order)
	go keeper(orders)
	for _, item := range []string{"apples", "pears", "apples"} {
		reply := make(chan int)
		orders <- order{item: item, reply: reply}
		fmt.Println(item, "left:", <-reply)
	}
}

The stock map lives inside keeper, so no other goroutine could reach it even by mistake.