53 lines
1006 B
Go
53 lines
1006 B
Go
// Copyright (c) 2024 Joshua Rich <joshua.rich@gmail.com>
|
|
//
|
|
// This software is released under the MIT License.
|
|
// https://opensource.org/licenses/MIT
|
|
|
|
package agent
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
)
|
|
|
|
// mergeCh merges a list of channels into a single channel. Essentially, fan-in for
|
|
// channels.
|
|
func mergeCh[T any](ctx context.Context, inCh ...<-chan T) chan T {
|
|
var wg sync.WaitGroup
|
|
|
|
outCh := make(chan T)
|
|
|
|
// Start an output goroutine for each input channel in sensorCh. output
|
|
// copies values from c to out until c is closed, then calls wg.Done.
|
|
output := func(ch <-chan T) { //nolint:varnamelen
|
|
defer wg.Done()
|
|
|
|
if ch == nil {
|
|
return
|
|
}
|
|
|
|
for n := range ch {
|
|
select {
|
|
case outCh <- n:
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
wg.Add(len(inCh))
|
|
|
|
for _, c := range inCh {
|
|
go output(c)
|
|
}
|
|
|
|
// Start a goroutine to close out once all the output goroutines are
|
|
// done. This must start after the wg.Add call.
|
|
go func() {
|
|
wg.Wait()
|
|
close(outCh)
|
|
}()
|
|
|
|
return outCh
|
|
}
|