package main
import (
"fmt"
"time"
"github.com/fatih/color"
)
func double(input chan int) chan int {
resultChan := make(chan int)
go func() {
defer close(resultChan)
for {
select {
case i, ok := <-input:
if ok == false {
color.Cyan("done its closed returing")
return
}
resultChan <- i + i
}
}
}()
return resultChan
}
func square(input chan int) chan int {
resultChan := make(chan int)
go func() {
defer close(resultChan)
for x := range input {
resultChan <- x * x
}
}()
return resultChan
}
func prefix(input chan int) chan string {
resultChan := make(chan string)
go func() {
defer close(resultChan)
for x := range input {
resultChan <- fmt.Sprintf("##### %d", x)
}
}()
return resultChan
}
func print_me(input chan string) {
go func() {
for {
select {
case x, ok := <-input:
if ok == false {
return
}
fmt.Println(x)
}
}
}()
}
func main() {
inputChan := make(chan int)
d := double(inputChan)
s := square(d)
p := prefix(s)
print_me(p)
for x := 0; x < 10; x++ {
inputChan <- x
time.Sleep(500 * time.Millisecond)
}
close(inputChan)
}
Hi @vizvasrj ,
Yes, this is a nice example of a pipeline. Let’s look at this pipeline:
stage one, in main(), you feed data (numbers) into a channel called inputChan
stage two, is the double method
stage three square
stage four prefix
stage five print_me
Please keep in mind that, while this is a basic example of the pipeline pattern, there are much more complex things that you can do in your stages. Take a look here for 6 cool solutions to various issues you may have with a pipeline: Go Concurrency Patterns: Pipelines and cancellation - The Go Programming Language