Para expandir alguns comentários sobre as respostas anteriores e fornecer uma comparação mais clara, aqui está um exemplo de ambas as abordagens apresentadas até agora com a mesma entrada, uma fatia de canais para ler e uma função para chamar para cada valor que também precisa saber qual canal de onde veio o valor.
Existem três diferenças principais entre as abordagens:
Complexidade. Embora possa ser parcialmente uma preferência do leitor, acho a abordagem do canal mais idiomática, direta e legível.
Atuação. No meu sistema Xeon amd64, o goroutines + channels executa a solução de reflexão em cerca de duas ordens de magnitude (em geral, a reflexão em Go é frequentemente mais lenta e só deve ser usada quando absolutamente necessário). Obviamente, se houver algum atraso significativo no processamento da função dos resultados ou na gravação dos valores nos canais de entrada, essa diferença de desempenho pode facilmente se tornar insignificante.
Semântica de bloqueio / buffer. A importância disso depende do caso de uso. Na maioria das vezes, isso não importa ou o pequeno buffer extra na solução de mesclagem de goroutine pode ser útil para o rendimento. No entanto, se for desejável ter a semântica de que apenas um único gravador seja desbloqueado e seu valor totalmente gerenciado antes que qualquer outro gravador seja desbloqueado, então isso só pode ser alcançado com a solução de reflexão.
Observe que ambas as abordagens podem ser simplificadas se o "id" do canal de envio não for necessário ou se os canais de origem nunca forem fechados.
Canal de fusão Goroutine:
// Process1 calls `fn` for each value received from any of the `chans`
// channels. The arguments to `fn` are the index of the channel the
// value came from and the string value. Process1 returns once all the
// channels are closed.
func Process1(chans []<-chan string, fn func(int, string)) {
// Setup
type item struct {
int // index of which channel this came from
string // the actual string item
}
merged := make(chan item)
var wg sync.WaitGroup
wg.Add(len(chans))
for i, c := range chans {
go func(i int, c <-chan string) {
// Reads and buffers a single item from `c` before
// we even know if we can write to `merged`.
//
// Go doesn't provide a way to do something like:
// merged <- (<-c)
// atomically, where we delay the read from `c`
// until we can write to `merged`. The read from
// `c` will always happen first (blocking as
// required) and then we block on `merged` (with
// either the above or the below syntax making
// no difference).
for s := range c {
merged <- item{i, s}
}
// If/when this input channel is closed we just stop
// writing to the merged channel and via the WaitGroup
// let it be known there is one fewer channel active.
wg.Done()
}(i, c)
}
// One extra goroutine to watch for all the merging goroutines to
// be finished and then close the merged channel.
go func() {
wg.Wait()
close(merged)
}()
// "select-like" loop
for i := range merged {
// Process each value
fn(i.int, i.string)
}
}
Seleção de reflexão:
// Process2 is identical to Process1 except that it uses the reflect
// package to select and read from the input channels which guarantees
// there is only one value "in-flight" (i.e. when `fn` is called only
// a single send on a single channel will have succeeded, the rest will
// be blocked). It is approximately two orders of magnitude slower than
// Process1 (which is still insignificant if their is a significant
// delay between incoming values or if `fn` runs for a significant
// time).
func Process2(chans []<-chan string, fn func(int, string)) {
// Setup
cases := make([]reflect.SelectCase, len(chans))
// `ids` maps the index within cases to the original `chans` index.
ids := make([]int, len(chans))
for i, c := range chans {
cases[i] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(c),
}
ids[i] = i
}
// Select loop
for len(cases) > 0 {
// A difference here from the merging goroutines is
// that `v` is the only value "in-flight" that any of
// the workers have sent. All other workers are blocked
// trying to send the single value they have calculated
// where-as the goroutine version reads/buffers a single
// extra value from each worker.
i, v, ok := reflect.Select(cases)
if !ok {
// Channel cases[i] has been closed, remove it
// from our slice of cases and update our ids
// mapping as well.
cases = append(cases[:i], cases[i+1:]...)
ids = append(ids[:i], ids[i+1:]...)
continue
}
// Process each value
fn(ids[i], v.String())
}
}
[Código completo no playground Go .]