給出以下簡單的Go程序package mainimport ( "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!謝謝你
2 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
由于您從不關閉ch通道,因此范圍循環將永遠不會結束。
您無法在同一頻道上發送結果。一種解決方案是使用不同的解決方案。
您的程序可以像這樣進行修改:
package main
import (
"fmt"
)
func total(in chan int, out chan int) {
res := 0
for iter := range in {
res += iter
}
out <- res // sends back the result
}
func main() {
ch := make(chan int)
rch := make(chan int)
go total(ch, rch)
ch <- 1
ch <- 2
ch <- 3
close (ch) // this will end the loop in the total function
result := <- rch // waits for total to give the result
fmt.Println("Total is ", result)
}
- 2 回答
- 0 關注
- 200 瀏覽
添加回答
舉報
0/150
提交
取消