Created
May 28, 2019 17:55
-
-
Save 777777miSSU7777777/a229efc1d088e611d611a0586c1226b7 to your computer and use it in GitHub Desktop.
Fan in example which merges all producers channels in single goroutine.
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" | |
| ) | |
| // Multiply simple function which returns channel with multiplied on m numbers in range (1, n). | |
| func Multiply(n, m int) <-chan int{ | |
| ch := make(chan int, n) | |
| go func(){ | |
| for i := 1; i < n; i++ { | |
| time.Sleep(time.Millisecond * 5) | |
| ch <- i * m | |
| } | |
| close(ch) | |
| }() | |
| return ch | |
| } | |
| // Merge merges channels without additional goroutines for each channel. | |
| func Merge(chans ...<-chan int) <-chan int { | |
| outputChan := make(chan int) | |
| counter, goal := 0, len(chans) | |
| go func(){ | |
| for { | |
| for _, c := range chans { | |
| select { | |
| case v, open := <-c: { | |
| if open { | |
| outputChan <- v | |
| } else { | |
| counter++ | |
| } | |
| } | |
| default: continue | |
| } | |
| if counter == goal { | |
| close(outputChan) | |
| break | |
| } | |
| } | |
| } | |
| }() | |
| return outputChan | |
| } | |
| // Example main. | |
| func main(){ | |
| s := []<-chan int {} | |
| for i := 1; i <= 10; i++ { | |
| s = append(s, Multiply(10, i)) | |
| } | |
| m := Merge(s...) | |
| for v := range m{ | |
| fmt.Println(v) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment