Go例程未接收通过通道发送的所有数据——玩具示例程序
我只是在玩Go例程未接收通过通道发送的所有数据——玩具示例程序,go,channel,goroutine,Go,Channel,Goroutine,我只是在玩Go,可以说是带着它试驾。我遇到了一个问题,一个打算接收3整数的go例程似乎只接收一个整数 type simpleFunction func() int func run(fChan chan simpleFunction, result chan int) { for{ select { case fn := <-fChan: fmt.Printf("sending: %d down result chan\n", fn()) re
Go
,可以说是带着它试驾。我遇到了一个问题,一个打算接收3
整数的go例程似乎只接收一个整数
type simpleFunction func() int
func run(fChan chan simpleFunction, result chan int) {
for{
select {
case fn := <-fChan:
fmt.Printf("sending: %d down result chan\n", fn())
result <- fn()
case <-time.After(time.Second * 2):
close(fChan)
}
}
}
func recieve(result chan int){
for {
select {
case x := <-result:
fmt.Printf("recieved: %d from result chan\n", x)
case <-time.After(time.Second * 2):
close(result)
}
}
}
这是我的输出:
sending a function that returns: 1 down function chan
sending: 1 down result chan
recieved: 1 from result chan
sending a function that returns: 2 down function chan
sending a function that returns: 3 down function chan
sending: 2 down result chan
sending: 3 down result chan
所以,正如你所看到的,第一个函数看起来一切都很顺利,但之后就不那么热了。有什么建议吗 此代码有几个问题:
- 当main返回时,程序终止。它不会等待
和运行
goroutines完成接收
- 有一场关于关闭频道的竞赛。无法保证发送方将在超时之前停止发送李>
- 如果main没有退出,那么{select{}循环的
将永远旋转打印零值。闭合通道上的接收返回零值李>
sending a function that returns: 1 down function chan
sending: 1 down result chan
recieved: 1 from result chan
sending a function that returns: 2 down function chan
sending a function that returns: 3 down function chan
sending: 2 down result chan
sending: 3 down result chan