dq804806 2012-12-27 06:55
浏览 23
已采纳

为什么我的频道陷入僵局?

I am trying to program a simple Go script that calculates the sum of the natural numbers up to 8:

package main
import "fmt" 

func sum(nums []int, c chan int) {
    var sum int = 0
    for _, v := range nums {
        sum += v    
    }
    c <- sum
}

func main() {
    allNums := []int{1, 2, 3, 4, 5, 6, 7, 8}
    c1 := make(chan int)
    c2 := make(chan int)
    sum(allNums[:len(allNums)/2], c1)
    sum(allNums[len(allNums)/2:], c2)
    a := <- c1
    b := <- c2
    fmt.Printf("%d + %d is %d :D", a, b, a + b)
}

However, running this program produces the following output.

throw: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.sum(0x44213af00, 0x800000004, 0x420fbaa0, 0x2f29f, 0x7aaa8, ...)
    main.go:9 +0x6e
main.main()
    main.go:16 +0xe6

goroutine 2 [syscall]:
created by runtime.main
    /usr/local/go/src/pkg/runtime/proc.c:221

exit status 2

Why is my code deadlocking? I am confused because I am using 2 separate channels to calculate the sub-sums. How are the two channels dependent at all?

  • 写回答

3条回答 默认 最新

  • dsf323233323332 2012-12-27 08:50
    关注

    Yes, you need to add go like

    go sum(allNums[:len(allNums)/2], c1)
    
    go sum(allNums[len(allNums)/2:], c2)
    

    or

    c1 := make(chan int,1)
    c2 := make(chan int,1)
    

    add channel cache.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?