Created
July 10, 2019 06:43
-
-
Save R4wm/ffa1d9092d7b7deeb8ca628afc4316e7 to your computer and use it in GitHub Desktop.
Fan In demonstration
This file contains 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" | |
"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