Channel capacity definition

Are these three statements equivalent?

in := make(chan int)
in := make(chan int, 0)
in := make(chan int, 1)

First statment is non buffered channel with cap 0, second statment is buffered channel with cap 0, third one is with 1 cap.

1 Like

You can test it by yourself.

func TestChanSize(t *testing.T) {
	c1 := make(chan int)
	c2 := make(chan int, 0)
	c3 := make(chan int, 1)
	t.Log("c1:size=", unsafe.Sizeof(c1), "len=", len(c1), "cap=", cap(c1))
	t.Log("c2:size=", unsafe.Sizeof(c2), "len=", len(c2), "cap=", cap(c2))
	t.Log("c3:size=", unsafe.Sizeof(c3), "len=", len(c3), "cap=", cap(c3))
}
//c1:size= 8 len= 0 cap= 0
//c2:size= 8 len= 0 cap= 0
//c3:size= 8 len= 0 cap= 1
  1. Is this program blocked while trying to write into channel on N+2 or on N+1 (where N is a capacity of the given channel)? Considering the output I could thought that blocking happens on N+2, but we know that it should be N+1, so where is the truth?

  2. If we place the line with output “generator finish” after close(out) than the output of the program will not always contains “generator finish” - why?

package main

import (
	"fmt"
)

func main() {
	in := make(chan int, 1)
	go func(out chan<- int) {
		for i := 0; i < 3; i++ {
			fmt.Println("before", i)
			out <- i
			fmt.Println("after", i)
		}
		fmt.Println("generator finish")
		close(out)
	}(in)
	for i := range in {
		fmt.Println("_____get", i)
	}
}

before 0
after 0
before 1
after 1
before 2
_____get 0
_____get 1
_____get 2
after 2
generator finish

Hi. The order of print outs could be “wrong” because you read from the channel before you print out in the loop at the bottom so the go routine can manage to write to the channel before the loop prints.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.