Created
May 10, 2018 02:53
-
-
Save xiazhibin/916ae26165a967865f727fe2b98b31c3 to your computer and use it in GitHub Desktop.
go concurrency pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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