mirror of
https://github.com/tmrts/go-patterns.git
synced 2026-02-04 14:46:19 +00:00
Add fan-in/out messaging patterns
This commit is contained in:
33
fan/fan_in.go
Normal file
33
fan/fan_in.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package fan
|
||||
|
||||
import "sync"
|
||||
|
||||
// In implements fan.In messaging pattern
|
||||
// Merges different channels in one channel
|
||||
func In(cs ...<-chan int) <-chan int {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
out := make(chan int)
|
||||
|
||||
// Start an send goroutine for each input channel in cs. send
|
||||
// copies values from c to out until c is closed, then calls wg.Done.
|
||||
send := func(c <-chan int) {
|
||||
for n := range c {
|
||||
out <- n
|
||||
}
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
wg.Add(len(cs))
|
||||
for _, c := range cs {
|
||||
go send(c)
|
||||
}
|
||||
|
||||
// Start a goroutine to close out once all the send goroutines are
|
||||
// done. This must start after the wg.Add call.
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(out)
|
||||
}()
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user