Pipelines in Go
Each stage reads a channel and returns one, so stages compose.
func generate(limit int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 1; i <= limit; i++ {
out <- i
}
}()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for value := range in {
out <- value * value
}
}()
return out
}
func sumPipeline(limit int) int {
total := 0
for value := range square(generate(limit)) {
total += value
}
return total
}
How it works
- Every stage closes the channel it owns.
- Stages run concurrently, so the work overlaps.
- The final range drains the last stage.
Keywords and builtins used here
chanclosedeferforfuncgointmakerangereturn
The run, in numbers
- Lines
- 29
- Characters to type
- 425
- Tokens
- 126
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 69 seconds.
Step 4 of 5 in Patterns, step 22 of 25 in Concurrency.