I am a newbie to Go. In my example below, multiple go routines are consuming from an unbuffered channel.
Code :
var c = make(chan int)
func f() {
for val := range c {
fmt.Printf("routine 1 : %v\n", val)
}
}
func g() {
fmt.Printf("routine 2 : %v\n", <-c)
}
func main() {
go f()
go g()
c <- 0
c <- 1
c <- 2
c <- 3
c <- 4
c <- 5
close(c)
}
The output was :
routine 1 : 0
routine 1 : 2
routine 2 : 1
routine 1 : 3
routine 1 : 4
Value 5 is missing from this and never gets printed ! Why is this happening? If I remove the call - go g()
, it works perfectly.
Also, if I make the channel buffered, say :
var c = make(chan int, 10)
There is no output at all. I understand that for unbuffered channel, the send completes after receive completes, which is not the case for buffered. Still, for buffered case, if channel has not yet sent any int, wouldn't the for loop be blocked considering it a nil channel?
Please help out with both my queries. Appreciate all the inputs.
As soon as
5
is consumed, the program exits. There's no time for it to print the output. If you run the program enough times, you may find that on some occasions, it does happen to print the output before it closes, but it'll be purely random.You need to add some mechanism to wait for your channels to finish, before exiting the program.