Created
December 20, 2022 18:15
-
-
Save nkcmr/933222ca1adac6c765a89f53c02750c4 to your computer and use it in GitHub Desktop.
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 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