1

I am wondering as to why buffered channels of length zero exist in the language. They seem to just yield deadlock in my experience. Is there any use for the at all?

  • 2
    Unbuffered channels allow to synchronize two goroutines by exchanging a value. – Volker Jan 10 '19 at 14:38
  • 3
    Actually, the rule of thumb when programming in Go is that if making a channel buffered fixes a problem, you have a logic bug. Buffered channels do have uses (two uses, actually) but most of the time you should _start_ with unbuffered channels. – kostix Jan 10 '19 at 14:42
  • 2
    "buffered channels of length zero" don't exist. If its length is zero, it is unbuffered, by definition. – Adrian Jan 10 '19 at 15:07

2 Answers2

4

From this answer (emphasis mine):

By default, a channel has a buffer size of 0 (you get this with make(chan int)). This means that every single send will block until another goroutine receives from the channel.

If you’re receiving deadlocks, then it’s likely that either nothing is reading from the channel, or something is writing faster than you can read.

MTCoster
  • 5,868
  • 3
  • 28
  • 49
4

A channel of size zero is unbuffered. This means that every single send will block until another goroutine receives from the channel. This example will work:

package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int, 0)
    go func() {
        for c := range ch {
            fmt.Println(c)
        }
    }()
    ch <- 1
    ch <- 2
    time.Sleep(time.Minute)
}
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143