package main import ( "context" "fmt" "time" ) func worker(ctx context.Context, jobs <-chan int, out chan<- int) { for { select { case <-ctx.Done(): return case n, ok := <-jobs: if !ok { return } out <- n * n } } } func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() jobs := make(chan int) out := make(chan int) go worker(ctx, jobs, out) go func() { defer close(jobs) for _, n := range []int{2, 3, 4} { jobs <- n } }() for i := 0; i < 3; i++ { fmt.Println(<-out) } }