package main import ( "fmt" "time" ) const bakers = 3 type Order struct { id int bread string bake time.Duration } type Loaf struct { order Order baker int } func frontCounter(list []Order, orders chan Order) { for _, order := range list { orders <- order } close(orders) } func baker(id int, orders chan Order, loaves chan Loaf) { for order := range orders { time.Sleep(order.bake) loaves <- Loaf{order: order, baker: id} } } func main() { ms := time.Millisecond list := []Order{ {1, "sourdough", 400 * ms}, {2, "baguette", 200 * ms}, {3, "rye", 300 * ms}, {4, "brioche", 100 * ms}, {5, "focaccia", 200 * ms}, {6, "pretzel", 100 * ms}, {7, "challah", 300 * ms}, {8, "bagel", 100 * ms}, {9, "ciabatta", 200 * ms}, } orders := make(chan Order) loaves := make(chan Loaf) start := time.Now() go frontCounter(list, orders) for id := 1; id <= bakers; id++ { go baker(id, orders, loaves) } made := make([]int, bakers+1) var alone time.Duration for range list { loaf := <-loaves made[loaf.baker]++ alone += loaf.order.bake at := time.Since(start).Round(10 * ms) fmt.Printf("%6v baker %d: order %d, %s\n", at, loaf.baker, loaf.order.id, loaf.order.bread) } fmt.Println() for id := 1; id <= bakers; id++ { fmt.Printf("baker %d made %d loaves\n", id, made[id]) } fmt.Println("together:", time.Since(start).Round(10*ms)) fmt.Println("one baker alone:", alone) } // Try this next… // // Set bakers to 1, then to 9, and run each. Which number makes "together" // match "one baker alone"? Which makes it match the slowest single loaf? // // Delete the go in front of frontCounter, so main sends the orders itself. // Read the error, then work out which goroutine is waiting for which. // Then give loaves a buffer with make(chan Loaf, len(list)) and run it again. // // Change the parameter types to orders <-chan Order and loaves chan<- Loaf // in baker. These are channels that can only receive and only send. Try // sending on orders inside baker and read what the compiler says. // // Give main a select with time.After so it stops waiting after half a // second, and prints which orders never came out of the oven. // // Have the bakers count their own loaves in a shared variable instead of // main counting them in made. Run it with go run -race . and read the report. // // Run go doc sync.WaitGroup and rewrite main so it waits for the bakers to // finish instead of counting loaves. Who should close the loaves channel now?