我对Go很陌生,我正在努力学习无缓冲频道和goroutines。
我有这个代码:
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)
}
所以我期望输出是:
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
相反,我得到:
1 * 2 = 2
1 * 4 = 4
fatal error: all goroutines are asleep - deadlock!
我真的不明白为什么第二个函数在第三个之后执行。如何在不将通道更改为缓冲通道的情况下获得结果。
慕盖茨4494581
相关分类