Created
September 9, 2020 20:18
-
-
Save rossedman/96e6ebe7a03a5db481e869ededa2bbae to your computer and use it in GitHub Desktop.
Go Fan Out/In 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" | |
"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