Go routine sample
package pipeline
import (
"fmt"
"testing"
)
func TestMerge(t *testing.T) {
ch1, ch2, ch3 := make(chan interface{}), make(chan interface{}), make(chan interface{})
out := Merge(ch1, ch2, ch3)
singleOut := func(c chan interface{}) {
for i := 0; i < 10; i++ {
c <- i
}
close(c)
}
go singleOut(ch1)
go singleOut(ch2)
go singleOut(ch3)
for n := range out {
fmt.Println(n)
}
}
package pipeline
import "sync"
// form http://blog.golang.org/pipelines
func Merge(cs ...<-chan interface{}) chan interface{} {
var wg sync.WaitGroup
out := make(chan interface{})
output := func(c <-chan interface{}) {
for data := range c {
out <- data
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
package main
import (
"fmt"
"time"
)
func main() {
lChan := make(chan int, 5)
lDone := make(chan bool)
go func() {
for i := 0; i < 3; i++ {
fmt.Println("Received: ", <-lChan)
}
close(lDone)
}()
for i := 0; i < 10; i++ {
select {
case lChan <- i:
fmt.Println("Sent: ", i)
case <- time.After(time.Minute):
//TODO: Here goes the code to handle what happens if the buffer is full
//or nobody is currently receiving data
}
}
<- lDone
fmt.Println("Finished!")
}