I'm setting up a chain of three goroutines, each with an input an output channel. The goroutines will read from the input channel until it's closed, increment the value, send it to the output channel. However, the program below deadlocks with this output:
goroutine 'one': 1
goroutine 'two': 2
goroutine 'three': 3
goroutine 'one': 10
goroutine 'two': 11
goroutine 'one': 100
fatal error: all goroutines are asleep - deadlock!
Code:
package main
import (
"fmt"
)
func int_channel(id string, i chan int, o chan int) {
defer close(o)
for x := range i {
fmt.Printf("goroutine '%s': %d
", id, x)
o <- x + 1
}
fmt.Println("done")
}
func main() {
c0 := make(chan int)
c1 := make(chan int)
c2 := make(chan int)
c3 := make(chan int)
go int_channel("one", c0, c1)
go int_channel("two", c1, c2)
go int_channel("three", c2, c3)
c0 <- 1
c0 <- 10
c0 <- 100
c0 <- 1000
c0 <- 10000
c0 <- 100000
close(c0)
fmt.Println("Sent all numbers to c0")
for x := range c3 {
fmt.Printf("out: %d
", x)
}
}