Chanells capacity problem

  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

2 posts were merged into an existing topic: Channel capacity definition