I am very new to Go and I am trying to learn about unbuffered channels and goroutines.
I have this code:
func main() {
var waitGroup sync.WaitGroup
waitGroup.Add(3)
c := make(chan int)
go func() {
defer waitGroup.Done()
x := 1
res := x * 2
fmt.Println(x, "* 2 = ", res)
c <- x
}()
go func() {
defer waitGroup.Done()
x := <-c
res := x * 3
fmt.Println(x, "* 3 = ", res)
c <- x
}()
go func() {
defer waitGroup.Done()
x := <-c
res := x * 4
fmt.Println(x, "* 4 = ", res)
}()
waitGroup.Wait()
close(c)
}
So i expect the output to be:
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
Instead I get:
1 * 2 = 2
1 * 4 = 4
fatal error: all goroutines are asleep - deadlock!
I really don't understand why the second func gets executed after the third. How can I get the result without changing the channel to a buffered channel.