Created
May 27, 2023 18:37
Go fanin pattern example
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" | |
) | |
func FaninProducer(inChans ...chan int) <-chan int { | |
outCh := make(chan int, len(inChans)) | |
for _, inCh := range inChans { | |
go func(inCh <-chan int) { | |
for v := range inCh { | |
outCh <- v | |
} | |
}(inCh) | |
} | |
return outCh | |
} | |
func producer() []chan int { | |
out := make([]chan int, 5) | |
for i := 0; i < 5; i++ { | |
out[i] = make(chan int, 0) | |
} | |
return out | |
} | |
func generator(inchs ...chan int) { | |
for { | |
time.Sleep(time.Second * 2) | |
for i, v := range inchs { | |
v <- i | |
} | |
} | |
} | |
func main() { | |
inChans := producer() | |
go generator(inChans...) | |
out := FaninProducer(inChans...) | |
for v := range out { | |
fmt.Println(v) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment