Channel Generator With Done Cancellation

A generator goroutine yields values through a receive-only channel, closes it on exit, and watches a done channel so early consumers never leak the producer.

GoResilience

Code

gosnippet
36 lines
package main

import "fmt"

// generate 返回只读通道,从 start 产出 count 个连续整数。
// done 关闭时生产者立即退出,避免 goroutine 泄漏。
func generate(start, count int, done <-chan struct{}) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out) // 离开 goroutine 时关闭,消费者的 range 才能结束
		for i := 0; i < count; i++ {
			select {
			case out <- start + i:
			case <-done:
				return
			}
		}
	}()
	return out
}

func main() {
	// 完整消费:done 永不关闭,range 一直读到 close(out) 为止
	all := generate(0, 4, make(chan struct{}))
	for v := range all {
		fmt.Println("value:", v)
	}

	// 提前取消:只取两个值后关闭 done,生产者不会再阻塞在发送上
	cancel := make(chan struct{})
	first := generate(10, 100, cancel)
	fmt.Println("got:", <-first)
	fmt.Println("got:", <-first)
	close(cancel)
	fmt.Println("cancelled early")
}

How it works

Channel Generator With Done Cancellation comes down to the functions generate and main.

A single loop drives the file — for i := 0; i < count; i++. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Cleanup is attached with defer, so it runs on every exit path of the function.

What to watch for

  • Nothing external — every call lands on the language’s built-in API surface.

Using it

Signature: func generate(start, count int, done <-chan struct{}) <-chan int

The demo output is labeled (value:, got:, cancelled early), so every line in the printed output names the step that produced it.

Running the file executes main, which drives generate in order.

The key statements, annotated

defer close(out) // 离开 goroutine 时关闭,消费者的 range 才能结束
all := generate(0, 4, make(chan struct{}))
cancel := make(chan struct{})

Interactive Tools for This Topic

FAQ

What does Channel Generator With Done Cancellation print when run?
Execute the whole file; each printed line is prefixed with a label like `value:`, `got:`, `cancelled early`.