Write a generator whose goroutine stops when its context is cancelled
Implement generate: it returns a channel that yields 0, 1, 2, … without end. When ctx is cancelled, the goroutine behind the channel stops and the channel is closed. Requirements: the goroutine exits even if the consumer stopped reading while a send was pending; no busy loop; an already cancelled context gives a channel that closes at once.
func generate(ctx context.Context) <-chan int {
// your code here
}Write the implementation.
Do not add extra imports unless the task says so explicitly.
Run a goroutine that does defer close(ch) and loops on select { case ch <- i: case <-ctx.Done(): return }. The select makes the blocked send cancellable, so a consumer that walks away cannot strand the goroutine.
- Checking
ctx.Err()between sends but doing a bare blockingch <- i, so the goroutine leaks on an abandoned channel - Closing the channel from another goroutine than the sender, which panics on a pending send
- Polling with
selectanddefaultin a loop, which spins a CPU core while nobody reads
- How would you check in a test that the goroutine really exited?
- Who should cancel the context when a consumer stops early?
Solution
A send into an unbuffered channel blocks until somebody reads. So checking ctx.Err() between sends is not enough: the consumer left, the goroutine hangs on ch <- i and never reaches the check. The send itself must be cancellable: select waits for either a reader or ctx.Done(). The goroutine that writes to the channel also closes it — defer close(ch): closing from other code while a send is pending panics. The ctx.Err() check before the select covers an already cancelled context: when both cases are ready (a reader is waiting and the context is done), select picks one at random and could send one more value.
func generate(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
defer close(ch) // signals the end of the stream
for i := 0; ; i++ {
if ctx.Err() != nil { // already cancelled: send nothing more
return
}
select {
case ch <- i: // send while somebody reads
case <-ctx.Done(): // cancel releases a hanging send
return
}
}
}()
return ch
}Whoever created the context owns cancel: a consumer that leaves early must call it (usually defer cancel()), otherwise the goroutine stays.