当收到C1和C2时,如何调整以下代码以执行某些操作 https://gobyexample.com/select
import "time"
import "fmt"
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(time.Second * 1)
c1 <- "one"
}()
go func() {
time.Sleep(time.Second * 2)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
答案 0 :(得分:3)
那可能是pipeline technique, called fan-in:
一个函数可以从多个输入读取并继续执行,直到通过将输入通道多路复用到所有输入都关闭时关闭的单个通道来关闭所有输入。这称为扇入。
func merge(cs ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan string)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed or it receives a value
// from done, then output calls wg.Done.
output := func(c <-chan string) {
for n := range c {
select {
case out <- "received " + n:
case <-done:
}
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
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(out)
}()
return out
}
查看complete example in this playground
注意:无论你最终使用什么解决方案,都会留下好的读物:
Principles of designing Go APIs with channels的{p> Alan Shreve。特别是:
API应声明其频道的方向性。