gpt4 book ai didi

Go routine 不接收通过 channel 发送的所有数据——玩具示例程序

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:34 25 4
gpt4 key购买 nike

我只是在玩 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)
}
}
}

因此,如您所见,run 例程接收函数,对其求值,然后将结果发送到 result channel 。

这是我的main/test:

func main() {
fns := []simpleFunction{
func() int {return 1},
func() int {return 2},
func() int {return 3},
}

fChan := make(chan simpleFunction)
result := make(chan int)

go run(fChan, result)
go recieve(result)
for _, fn := range fns {
fmt.Printf("sending a function that returns: %d down function chan\n", fn())
fChan <- fn
}
}

这是我的输出:

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 返回时终止。它不会等待 runreceive goroutines 完成。
  • 有一场关于关闭 channel 的竞赛。不能保证发件人会在超时之前发送。
  • 如果 main 不退出,则 for { select { } } 循环将永远旋转并打印零值。在关闭的 channel 上接收返回零值。

关于Go routine 不接收通过 channel 发送的所有数据——玩具示例程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com