Skip to content

Instantly share code, notes, and snippets.

@rossedman
Created September 9, 2020 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossedman/96e6ebe7a03a5db481e869ededa2bbae to your computer and use it in GitHub Desktop.
Save rossedman/96e6ebe7a03a5db481e869ededa2bbae to your computer and use it in GitHub Desktop.
Go Fan Out/In Example
package main
import (
"fmt"
"sync"
)
func main() {
ids := generator("id1", "id2", "id3", "id4", "id5", "id6")
for r := range merge(fan("one", ids), fan("two", ids), fan("three", ids)) {
fmt.Println(r)
}
}
func generator(ids ...string) <-chan string {
res := make(chan string)
go func() {
defer close(res)
for _, id := range ids {
res <- id
}
}()
return res
}
func fan(name string, ids <-chan string) <-chan string {
res := make(chan string)
go func() {
defer close(res)
for id := range ids {
res <- fmt.Sprintf("fan %s: %s", name, id)
}
}()
return res
}
func merge(chans ...<-chan string) <-chan string {
var wg sync.WaitGroup
wg.Add(len(chans))
res := make(chan string)
for _, c := range chans {
go func(c <-chan string) {
defer wg.Done()
for n := range c {
res <- n
}
}(c)
}
go func() {
wg.Wait()
close(res)
}()
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment