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 | |
} | |
} | |
} |
This comment has been minimized.
This comment has been minimized.
@kylehq, looks like the process is more about handling passing channels over a number of functions (some of which may be third party) like when dealing with a HTTP request: https://blog.golang.org/context/google/google.go Still looks like a standard |
This comment has been minimized.
This comment has been minimized.
Is it required to call |
This comment has been minimized.
This comment has been minimized.
@gerep It is duplicated I believe. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Hi Jaana, thanks so much for putting all these together. I'd like to ask a question in regards to the above and your post https://rakyll.org/leakingctx/.
Can you explain to me why it's better to pass a
context
to thegen()
function rather than astop chan struct{}
? The gen function would still have the same method changes, both ways will use a single dependency and the stop can also be deferred to ensure no goroutine leaks.Is this just a new convention? Is there a performance gain to using the context instead? Any thoughts would be most welcome =]
Thanks Kyle