Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Last active August 29, 2015 14:03
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 egonelbre/44bf352952f96df7ce57 to your computer and use it in GitHub Desktop.
Save egonelbre/44bf352952f96df7ce57 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"gopkg.in/tomb.v2"
)
type Pipeline struct {
tomb.Tomb
next int
numbers chan int
filtered chan int
}
func NewPipeline() *Pipeline {
p := &Pipeline{}
p.numbers = make(chan int)
p.filtered = make(chan int)
p.Go(p.generate)
p.Go(p.filter)
p.Go(p.print)
return p
}
func (p *Pipeline) generate() error {
for {
select {
case p.numbers <- p.next:
case <-p.Dying():
return nil
}
p.next += 1
}
return nil
}
func (p *Pipeline) filter() error {
v := 0
for {
select {
case v = <-p.numbers:
case <-p.Dying():
return nil
}
if v%2 == 1 {
continue
}
select {
case p.filtered <- v:
case <-p.Dying():
return nil
}
}
return nil
}
func (p *Pipeline) print() error {
for {
select {
case v := <-p.filtered:
if v > 10 {
return p.Killf("the number %v is too big", v)
}
fmt.Println(v)
case <-p.Dying():
return nil
}
}
return nil
}
func main() {
p := NewPipeline()
if err := p.Wait(); err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment