Skip to content

Instantly share code, notes, and snippets.

@17twenty
Forked from rakyll/gist:1aa860377dab8fd445431bbb3204f600
Created November 15, 2016 05:36
Show Gist options
  • Save 17twenty/6ce02474f682ca76237f784de9f785fb to your computer and use it in GitHub Desktop.
Save 17twenty/6ce02474f682ca76237f784de9f785fb to your computer and use it in GitHub Desktop.
How to Not Leak Go Routines using Contexts
package main
import (
"context"
"fmt"
)
func gen(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
var n int
for {
select {
case <-ctx.Done():
return
case ch <- n:
n++
}
}
}()
return ch
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
cancel()
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment