duanlvxing7707 2013-03-19 23:35
浏览 11
已采纳

Go中的死锁,两个例程分开工作

I'm a bit stuck on a deadlock issue in go.

This program takes an array of ints, a, and splits it into two. Then it takes these two parts in two different routines and sum up all elements. After this, it's supposed to send the two results in the channel res. The two res (now ch) then should be added together and print.

My problem: I've tried to tackle the deadlock problem by moving about close-functions a lot, but nothing seems to help. It works well with only one routine Add running obviously.

package main

import (
    "fmt"
)

// Add adds the numbers in a and sends the result on res.
func Add(a []int, res chan<- int) {
    sum := 0
    for i := range a {
        sum = sum + a[i]
    }
    res <- sum
}

func main() {
    a := []int{1, 2, 3, 4, 5, 6, 7}

    n := len(a)
    ch := make(chan int)
    go Add(a[:n/2], ch)
    go Add(a[n/2:], ch)


    sum := 0
    for s := range ch {
        sum = sum + s
    }
    //close(ch)

    fmt.Println(sum)
}
  • 写回答

1条回答 默认 最新

  • doujiene2845 2013-03-19 23:51
    关注

    You're never closing the channel so there's no signal for the range to quit. It'll just keep on trying to receive, but there's nothing left that's sending.

    You would either need to have some way for your Add() function to see when it ends if it is the last one so that it can close() the channel, or you could just decrement a counter instead of using range in the loop so that you don't need to use close().

    func main() {
        a := []int{1, 2, 3, 4, 5, 6, 7}
    
        n := len(a)
        ch := make(chan int)
        go Add(a[:n/2], ch)
        go Add(a[n/2:], ch)
    
        sum := 0
    
        // counts the number of messages sent on the channel
        count := 0
    
        // run the loop while the count is less than the total number of routines
        for count < 2 {
            s := <-ch
            sum = sum + s
            count++  // Increment the count after a routine sends its value
        }
        fmt.Println(sum)
    }
    

    DEMO: http://play.golang.org/p/oHcrUStjmm

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改