【问题标题】:Go routine not receiving all data sent through channel -- toy example programGo 例程没有接收到通过通道发送的所有数据——玩具示例程序
【发布时间】:2015-12-29 09:32:04
【问题描述】:

我只是在玩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 通道。

这是我的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

所以,如您所见,第一个函数似乎一切顺利,但之后就不那么热了。有什么提示或建议吗?

【问题讨论】:

    标签: go channel goroutine


    【解决方案1】:

    这段代码有几个问题:

    • 程序在 main 返回时终止。它不会等待 run 和 receive goroutine 完成。
    • 有一场关于关闭频道的竞赛。不能保证发件人会在超时之前发送。
    • 如果 main 没有退出,那么 for { select { } } 循环将永远旋转并打印零值。在关闭的通道上接收返回零值。

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2020-12-28
      • 2018-03-21
      • 2018-07-03
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2021-03-14
      相关资源
      最近更新 更多