Created
July 8, 2019 07:57
-
-
Save sillyfellow/d6a582ee26db2175a76d51b1106c0c4b to your computer and use it in GitHub Desktop.
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" | |
) | |
// fillChannel simply fills the channel with i, i+2, i+4, ... | |
func fillChannel(ch chan int, i int) { | |
for { | |
ch <- i | |
i += 2 | |
} | |
} | |
// evenChannel returns a channel which has all the even positive integers | |
func evenChannel() <-chan int { | |
evens := make(chan int) | |
go fillChannel(evens, 0) | |
return evens | |
} | |
// evenChannel returns a channel which has all the odd positive integers | |
func oddChannel() <-chan int { | |
odds := make(chan int) | |
go fillChannel(odds, 1) | |
return odds | |
} | |
// mergeChannels takes a slice of channels, returns a channel which is the | |
// n-way-merge of all channels from the input | |
func mergeChannels(channels []<-chan int) <-chan int { | |
merged := make(chan int) | |
for _, ch := range channels { | |
go func(c <-chan int) { | |
for incoming := range c { | |
// process incoming value if needed. | |
merged <- incoming | |
} | |
}(ch) | |
} | |
return merged | |
} | |
func main() { | |
// merging odd and even channels will give us all the integers | |
integers := mergeChannels([]<-chan int{ | |
evenChannel(), | |
oddChannel(), | |
}) | |
// let's print them out. | |
for i := range integers { | |
fmt.Println(i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment