Skip to content

Instantly share code, notes, and snippets.

@R4wm
Created July 10, 2019 06:43
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 R4wm/ffa1d9092d7b7deeb8ca628afc4316e7 to your computer and use it in GitHub Desktop.
Save R4wm/ffa1d9092d7b7deeb8ca628afc4316e7 to your computer and use it in GitHub Desktop.
Fan In demonstration
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println("start main")
c := dostuff("Raymond")
d := dostuff("Brandy")
fanned := myFanIn(c, d)
for i := 0; ; i++ {
fmt.Printf("This is stuff: %s\n", <-fanned)
}
fmt.Println("Done")
}
func dostuff(word string) <-chan string {
c := make(chan string)
// If there is no go func here, it will not run..
// Reason:
go func() {
for i := 0; ; i++ {
c <- word
time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
}
}()
return c
}
func myFanIn(a, b <-chan string) <-chan string {
result := make(chan string)
go func() {
for {
select {
case fromA := <-a:
result <- fromA
case fromB := <-b:
result <- fromB
}
}
}()
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment