dongliao8069 2013-11-21 06:21 采纳率: 0%
浏览 41
已采纳

Golang:有关频道的一些问题

http://play.golang.org/p/uRHG-Th_2P

I am having hard time understanding the concept of channel

package main

import (
  "fmt"
)

func Fibonacci(limit int, chnvar chan int) {
  x, y := 0, 1
  for i := 0; i < limit; i++ {
    chnvar <- x
    x, y = y, x+y
  }
  close(chnvar)

  v, ok := <-chnvar
  fmt.Println(v, ok)
}


func main() {
  chn := make(chan int, 10)
  go Fibonacci(cap(chn), chn)
  for elem := range chn {
    fmt.Printf("%v ", elem)
  }
}
//1 1 2 3 5 8 13 21 34 

1) How do I get false value from the line

v, ok := <-chnvar

It says false if there are no more values to get. and also false if the channel is closed. But in this case, the channel is closed but(?) still get the true value.

And if I take out the close, it panics.

How and why it returns true here?

2) The line

 go Fibonacci(cap(chn), chn)

also runs without goroutine. What is the difference? Just matter of performance.

Thanks in advance

  • 写回答

2条回答 默认 最新

  • doukao2180 2013-11-21 07:51
    关注
    1. Your Fibonacci function stuffs 10 values into the channel (which has a buffer of 10 values), and then closes it. Assuming the v, ok <- chnvar statement executes before the main goroutine reads everything out of the channel (very likely, but not guaranteed), there will be a value to read so ok will be true.

      If you remove the close call, the for loop in the main goroutine will eventually empty the channel's buffer and block waiting for more data. Since there is no other goroutine active to write to the channel, the runtime detects this as a deadlock.

    2. Your sample program runs with Fibonacci called directly (not as a goroutine) because the channel it writes to is buffered, and it never overruns the buffer. Therefore it can complete without blocking and allows execution to continue to the rest of the main function.

      If the channel was not buffered, or you wrote more values than would fit in the buffer, then Fibonacci would block waiting for some other goroutine to read something from the channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致