Skip to content

Instantly share code, notes, and snippets.

@betandr
Created July 8, 2020 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betandr/a629f50e58696b85032c6c95408e3fe8 to your computer and use it in GitHub Desktop.
Save betandr/a629f50e58696b85032c6c95408e3fe8 to your computer and use it in GitHub Desktop.
Go "done-channel" pattern
package main
import (
"fmt"
"time"
)
// multiples uses a done channel to shut down
func multiples(i int) (chan int, chan struct{}) {
out := make(chan int)
done := make(chan struct{})
current := 0
go func() {
for {
select {
case out <- current * i:
current++
case <-done:
fmt.Println("goroutine done")
return
}
}
}()
return out, done
}
func main() {
twosChan, done := multiples(2)
for i := range twosChan {
if i > 20 {
break
}
fmt.Println(i)
}
close(done) // signals the goroutines to end
time.Sleep(1 * time.Second) // simulate some work
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment