我试图理解为什么在这个 select
声明第一种情况总是关闭并且不等待 channel 被填充。对于这个程序,我试图让程序等待,直到所有 channel 都被填充,并且每当一个 channel 被方法填充时,它被放入 channel 数组中的第一个可用空间
我试着把 <-res[i]
这行在 case 语句中,但由于某种原因,无论 channel 是否有值(value),这种情况总是会发生。
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func numbers(sz int) (res chan float64) {
res = make(chan float64)
go func() {
defer close(res)
num := 0.0
time.Sleep(time.Duration(rand.Intn(1000)) *time.Microsecond)
for i := 0; i < sz; i++ {
num += math.Sqrt(math.Abs(rand.Float64()))
}
num /= float64(sz)
res <- num
return
}()
return
}
func main() {
var nGo int
rand.Seed(42)
fmt.Print("Number of Go routines: ")
fmt.Scanf("%d \n", &nGo)
res := make([]chan float64, nGo)
j:=0
for i := 0; i < nGo; i++ {
res[i] =numbers(1000)
}
for true{
for i := 0; i < nGo; {
select {
case <-res[i]:{
res[j]=res[i]//this line
j++
}
default:
i++
}
}
if j==nGo{
break
}
}
fmt.Println(<-res[nGo-1])
}
打印行应该打印一些 float 。
最佳答案
<-res[i]
in the case statement but for some reason this case always goes off regarless of wether or not the channels has a value
如果 channel 的缓冲区已满(即无法在不阻塞的情况下发送值),它只会不会选择这种情况。您的 channel 的缓冲区长度等于您在其上发送的值的数量,因此它永远不会阻塞,因此没有理由接受 default
。案例。
关于go - 我试图理解为什么这个案子总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466011/