FAQ
Hi All,

Let say i have one buffered channel with 10 buffer

var c chan(string)
c = make(chan string, 10)

Then we fill channel with more than buffered

go func(){
     for i:=0 ; i<25 ; i++ {
          go func(){
               c <- "test string"
          }
     }
}()

Let say we only consume only 10

for i:= 0; i<5; i++ {
      <- c
}

We know here there are 10 items in buffered channel and another 10 are
blocked.

if we want to close the channel now, how we do it?
if we do we close(c), there would be panic for 10 items that all blocked.

do we need to consume first?
Like this :

go func() {
     for _ = range c {
     }
}

// to make sure all c are consumed.
time.Sleep(1 * time.Second)

close(c)


Any suggestion?

-W





--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Search Discussions

  • Ian Lance Taylor at Nov 16, 2013 at 5:09 am

    On Fri, Nov 15, 2013 at 8:19 PM, wrote:
    if we want to close the channel now, how we do it?
    if we do we close(c), there would be panic for 10 items that all blocked.
    General rule: only the goroutine that is sending values on a channel
    should close it. A goroutine that is receiving values from a channel
    should not close it.

    Ian

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/groups/opt_out.
  • Ibrahim M. Ghazal at Nov 16, 2013 at 5:22 am
    Closing is used to signal from the producer to the consumer, not the
    other way around. Even then, the consumer will not know the channel
    has been closed until it has read all the buffered values from it.

    If you need the consumer to tell the producer to stop sending, you'll
    need a second channel and select on it in the producer.

    Also note that closing channels is not required, so only use it as a
    signal. An unclosed channel will be garbage collected when there are
    no references to it, even if it's buffered and has values in it.

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/groups/opt_out.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedNov 16, '13 at 5:06a
activeNov 16, '13 at 5:22a
posts3
users3
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase