Skip to content

Instantly share code, notes, and snippets.

@xiazhibin
Created May 10, 2018 02:53
Show Gist options
  • Save xiazhibin/916ae26165a967865f727fe2b98b31c3 to your computer and use it in GitHub Desktop.
Save xiazhibin/916ae26165a967865f727fe2b98b31c3 to your computer and use it in GitHub Desktop.
go concurrency pattern
package main
import (
"fmt"
"time"
"math/rand"
)
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.")
}
func fanIn(inputs ... <-chan string) <-chan string {
c := make(chan string)
for _, input := range inputs {
go func(i <-chan string) {
for {
c <- <-i
}
}(input)
}
return c
}
func boring(msg string) <-chan string {
c := make(chan string)
go func() {
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment