dtmsaqtly798322992 2013-12-18 21:12
浏览 36
已采纳

缓冲通道关闭TRUE?

I have some questions... on Buffered Channel

Q1.

Then why the NonBuffered never outputs the TRUE value?

Does this mean the unbuffered channel is always closed? Then how come the unbuffered channel still produce the right outcome of fibonacci calculation?


Q2.

Why the NonBuffered output gets cut in the middle like the following?

    0 1 1 2 NB value: 0
    NB ok: false
    3

It should be something related with goroutine but Why in this way?


It is hard to understand because if I buffer this channel I get true value but with unbuffered channel I get only false...

Please check out the following link.

http://play.golang.org/p/O2Th61DfEY

package main

import "fmt"

func main() {
  ch := make(chan int)

  go NB(5, ch)
  for i := range ch {
    fmt.Printf("%d ", i)
  }
  /*
    0 1 1 2 NON_Buffered value: 0
    NON_Buffered ok: false
    3
  */

  fmt.Println()
  value, ok := <-ch
  fmt.Println("MAIN = NB value:", value)
  fmt.Println("MAIN = NB ok:", ok)
}

func NB(n int, ch chan int) {
  x, y := 0, 1
  for i := 0; i < n; i++ {
    ch <- x
    x, y = y, x+y
  }
  close(ch)
  value, ok := <-ch
  fmt.Println("NB value:", value)
  fmt.Println("NB ok:", ok)
}

Thanks a lot!

  • 写回答

2条回答 默认 最新

  • dongzongpeng6474 2013-12-18 22:44
    关注

    Q1: You never do value, ok <- ch on an un-closed channel: in NB you execute this statement after closing ch, and in main you execute it after reading all from ch in the for loop. Why do you expect to ever return ok==true to indicate the channel is un-closed?

    Q2: Once 3 is consumed from ch in main NB may run again and print before main starts printing. You have absolutely no synchronization between NB and main. Again: What do you expect from such code?

    If you want to emulate a generator for fibonacci numbers you should not read in NB from ch. This has nothing to do with buffering. Buffered channels just allow some goroutines to execute longer before blocking on the channel send.

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

报告相同问题?

悬赏问题

  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆