【发布时间】:2018-02-18 22:38:15
【问题描述】:
我是golang 的新手,遇到了问题。
我有几个channels。
一些有效载荷在不同的时间到达这个通道。
如何在频道准备吐出时从频道中一一获取所有值。
例如我写了这段代码:
主包
import (
"fmt"
"time"
"math/rand"
)
func main() {
arr1 := []int8{1,2,3,4,5}
arr2 := []int8{6,7,8,9,10}
c1 := make(chan int8)
c2 := make(chan int8)
go func() {
for _, val := range arr1 {
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
c1 <- val
}
}()
go func() {
for _, val := range arr2 {
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
c2 <- val
}
}()
select {
case res1 := <- c1:
fmt.Println(res1)
case res2 := <- c2:
fmt.Println(res2)
}
fmt.Println("Hello, test")
}
但在这种情况下,我只从其中一个渠道获得第一个值。
请给我建议如何解决我的问题。
【问题讨论】:
-
一种方法是将通道合并为一个并覆盖它。请参阅
fan-in示例here
标签: go