-
Notifications
You must be signed in to change notification settings - Fork 271
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
4. Concurrency Patterns in Go ->Pipelines ->Some Handy Generators
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
concurrency-patterns-in-go/pipelines/some-handy-generators/fig-take-and-repeatfn-pipeline.go
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
) | ||
|
||
func main() { | ||
repeatFn := func( | ||
done <-chan interface{}, | ||
fn func() interface{}, | ||
) <-chan interface{} { | ||
valueStream := make(chan interface{}) | ||
go func() { | ||
defer close(valueStream) | ||
for { | ||
select { | ||
case <-done: | ||
return | ||
case valueStream <- fn(): | ||
} | ||
} | ||
}() | ||
return valueStream | ||
} | ||
take := func( | ||
done <-chan interface{}, | ||
valueStream <-chan interface{}, | ||
num int, | ||
) <-chan interface{} { | ||
takeStream := make(chan interface{}) | ||
go func() { | ||
defer close(takeStream) | ||
for i := 0; i < num; i++ { | ||
select { | ||
case <-done: | ||
return | ||
case takeStream <- <-valueStream: | ||
} | ||
} | ||
}() | ||
return takeStream | ||
} | ||
done := make(chan interface{}) | ||
defer close(done) | ||
|
||
rand := func() interface{} { return rand.Int() } | ||
|
||
for num := range take(done, repeatFn(done, rand), 10) { | ||
fmt.Println(num) | ||
} | ||
} |