-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
53 lines (42 loc) · 880 Bytes
/
channel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package gokit
import (
"sync"
)
// FanOut is a function that will fan out the input channel to multiple workers
func FanOut[T any](input <-chan T, workerNum int, worker func(v T)) (done <-chan struct{}) {
doneC := make(chan struct{})
go func() {
defer close(doneC)
var wg sync.WaitGroup
for i := 0; i < workerNum; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for v := range input {
worker(v)
}
}()
}
wg.Wait()
}()
return doneC
}
// FanIn is a function that will fan in multiple input channels to a single output channel
func FanIn[T any](input ...<-chan T) <-chan T {
output := make(chan T)
go func() {
defer close(output)
var wg sync.WaitGroup
for _, v := range input {
wg.Add(1)
go func(c <-chan T) {
defer wg.Done()
for v := range c {
output <- v
}
}(v)
}
wg.Done()
}()
return output
}