考慮下面這個簡單的圍棋程序扔:所有夠程都睡着了 - 死鎖
package main
import (
"fmt"
)
func total(ch chan int) {
res := 0
for iter := range ch {
res += iter
}
ch <- res
}
func main() {
ch := make(chan int)
go total(ch)
ch <- 1
ch <- 2
ch <- 3
fmt.Println("Total is ", <-ch)
}
我想知道,如果有人可以告訴我,爲什麼我得到
throw: all goroutines are asleep - deadlock!
謝謝
不直接相關的問題,但仍然是有趣的瞭解夠程:如果添加'fmt.Println(「退出總」)''後出< - res'你可能再也看不到它,因爲程序可能會更快退出,而無需等待goroutine完成。 –
我開始學習前幾天,我不明白howcome res:= 0只運行一次?整個功能是否應該運行3次?在你的例子中,只有循環運行3次。 – if237912print
@OybekToirov整個函數只運行一次,每次int'in'通道中有迭代時迭代進行 –