Skip to content

Instantly share code, notes, and snippets.

@smanurung
Created September 25, 2015 17:57
Show Gist options
  • Save smanurung/c4d055aa608c00f51fcb to your computer and use it in GitHub Desktop.
Save smanurung/c4d055aa608c00f51fcb to your computer and use it in GitHub Desktop.
boring go concurrency pattern
package main
/**
* simple go concurrency pattern
* generator + fanIn
*/
import (
"fmt"
"math/rand"
"time"
)
/**
* fanIn listens to both channel and send the message to main goroutine.
*/
func fanIn(i, j <-chan string) <-chan string {
c := make(chan string)
go func() { for { c <- <-i }}()
go func() { for { c <- <-j }}()
return c
}
/**
* boring returns `receive` chan of string and constantly put string into the channel
*/
func boring(s string) <-chan string {
c := make(chan string)
go func() {
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", s, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c
}
func main() {
c := fanIn(boring("joe"), boring("ann"))
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
fmt.Println("You're both boring. I'm leaving")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment