What are the length and capacity of an unbuffered channel and why are they not getting printed in another go routine?

Viewed 29

I was trying to check the length of a channel after seeing the cap function used in this tutorial on buffered channels. I thought that the length would give the items in the channel that have been sent to the channel. I wrote a test program to check my reasoning. I started with an empty channel and expected both length and capacity to be 0.

    var c chan int = make(chan int)
    fmt.Println("len =", len(c))
    fmt.Println("cap =", cap(c))

    c <- 1

    fmt.Println("len =", len(c))
    fmt.Println("cap =", cap(c))

The first to fmt.Println gave the expected answer. However, when I sent something to the channel, I got a fatal error when I was expecting both the length and capacity to be the same - that is, increase by 1.

len = 0
cap = 0
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
        <filePath>.go:20 +0x148
exit status 2

Questions:

  • Why am I getting this error after adding c <-1?

  • If I don't make it a buffered channel, would the length and the capacity of the channel grow like the length of slices, if there is a way to fix this error?

I extended my code above to include a function that I would send to the channel instead of the main function thinking that there is only one goroutine and that the channel may need 2 go routines to work. However, I don't see anything getting printed from the testChannel function.

  • why is this so?
func testChannel(c chan int) {
    fmt.Println("in testChannel len =", len(c))
    fmt.Println("in testChannel cap =", cap(c))
    c <- 1
    fmt.Println("in testChannel len =", len(c))
    fmt.Println("in testChannel cap =", cap(c))
}

func main() {

    var c chan int = make(chan int)
    fmt.Println("len =", len(c))
    fmt.Println("cap =", cap(c))

    go testChannel(c)
}

The output is:

len = 0
cap = 0
0 Answers
Related