Created
November 6, 2013 21:46
-
-
Save AndrewWDeane/7344659 to your computer and use it in GitHub Desktop.
Dynamic Input Channels
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" | |
| "math" | |
| "time" | |
| ) | |
| func main() { | |
| producerA := producer(1) | |
| producerB := producer(10) | |
| consumerA := consumer("A") | |
| consumerB := consumer("B") | |
| i := 0.0 | |
| for { | |
| if math.Mod(i, 2) == 0.0 { | |
| consumerA <- producerA | |
| consumerB <- producerB | |
| } else { | |
| consumerA <- producerB | |
| consumerB <- producerA | |
| } | |
| time.Sleep(10e9) | |
| i++ | |
| } | |
| } | |
| func producer(f int) chan int { | |
| c := make(chan int, 10) | |
| go func() { | |
| i := 0 | |
| for { | |
| c <- i * f | |
| time.Sleep(1e9) | |
| i++ | |
| } | |
| }() | |
| return c | |
| } | |
| func consumer(s string) chan chan int { | |
| from := make(chan chan int) | |
| var input chan int | |
| go func() { | |
| for { | |
| select { | |
| case input = <-from: | |
| case i := <-input: | |
| fmt.Printf("%v:%v\n", s, i) | |
| } | |
| } | |
| }() | |
| return from | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment