×

go · level 3 · unit 6 · lesson 1

  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

A carries a stop signal to every goroutine that holds it.

A context carries a stop signal through your program. Start from context.Background(), an empty context that is never cancelled. context.WithCancel(parent) hands back a new context and a cancel function. Calling cancel() closes the context's Done() channel, the same broadcast trick as a done channel.

A goroutine handed the context watches for with case <-ctx.Done(): in its select, and stops. Afterwards ctx.Err() says why: context.Canceled, which prints with American spelling as context canceled.

Always call cancel, even when the work finished by itself; defer cancel() is the usual way. Calling it twice is harmless.

package main
import (
	"context"
	"fmt"
)
func countSheep(ctx context.Context, out chan<- int) {
	for n := 1; ; n++ {
		select {
		case out <- n:
		case <-ctx.Done():
			return
		}
	}
}
func main() {
	ctx, cancel := context.WithCancel(context.Background())
	sheep := make(chan int)
	go countSheep(ctx, sheep)
	fmt.Println(<-sheep, <-sheep, <-sheep)
	cancel()
	fmt.Println("stopped:", ctx.Err())
}

for n := 1; ; n++ has no condition, so it counts on until something stops it.