Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

This is do to how the channel Close operation works. The most interesting part of the output is that for the buffered, NB ok (the non-MAIN version) is true, but the VB value is still 0. It's returning 0 because it's closed, but since all the values haven't yet been read, it's not drained (all sent values have been received). I'm not sure about why the output orders differently - I think it's non deterministic.

However, @Volker's answer is probably the more useful one. Your program is doing a number of things incorrectly, albeit interesting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top