Created
July 8, 2020 15:43
-
-
Save betandr/a629f50e58696b85032c6c95408e3fe8 to your computer and use it in GitHub Desktop.
Go "done-channel" pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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