Skip to content

Instantly share code, notes, and snippets.

@nkcmr
Created December 20, 2022 18:15
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 nkcmr/933222ca1adac6c765a89f53c02750c4 to your computer and use it in GitHub Desktop.
Save nkcmr/933222ca1adac6c765a89f53c02750c4 to your computer and use it in GitHub Desktop.
package chanutil
import (
"context"
"sync"
)
func fanIn[T any](ctx context.Context, size int, chans ...<-chan T) <-chan T {
var wg sync.WaitGroup
copy := func(i <-chan T, o chan<- T) {
COPY_LOOP:
for {
select {
case v, ok := <-i:
if !ok {
break COPY_LOOP
}
select {
case <-ctx.Done():
break COPY_LOOP
case o <- v:
}
case <-ctx.Done():
break COPY_LOOP
}
}
wg.Done()
}
out := make(chan T, size)
for _, c := range chans {
wg.Add(1)
go copy(c, out)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment