du131642 2018-11-05 05:11
浏览 69
已采纳

具有多个通道的多个goroutine的死锁

I am working on a sample program to print sum of odd and sum of even number between 1 to 100 using goroutine with multiple channels.

you can find my code

here

output

sum of even number = 2550
sum of odd number = 2500
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.print(0x434100, 0x11db7c)
    /tmp/sandbox052575152/main.go:18 +0xc0
main.main()
    /tmp/sandbox052575152/main.go:14 +0x120

The code works but with deadlock. I am not sure what is wrong in my code

  • 写回答

1条回答 默认 最新

  • duansen6750 2018-11-05 05:58
    关注

    We can iterate through values sent over a channel. To break such iteration channel needs to be closed explicitly. Otherwise range would block forever in the same way as for nil channel. In your code you did't close the sum(for print function sumValues channel) channel. That's why following function will be blocked for forever.

    func print(sumValues <-chan string ){
        for val := range sumValues {
            fmt.Println(val)
        }
    }
    

    So you have to close the sum channel in the doSum function after all the go routine in the doSum function are complete (otherwise sum channel might be closed before go routines are complete). You can use sync.WaitGroup to do that. See the updated doSum function below:

    func doSum(sum chan<- string, oddChan <-chan int, evenChan <-chan int) {
        var waitGroup sync.WaitGroup
    
        waitGroup.Add(2) // Must wait for 2 calls to 'done' before moving on
    
        go func(sum chan<- string) {
            s1 := 0
            for val := range oddChan {
                s1 += val
            }
            sum <- fmt.Sprint("sum of odd number = ", s1)
            waitGroup.Done()
        }(sum)
    
        go func(sum chan<- string) {
            s1 := 0
            for val := range evenChan {
                s1 += val
            }
            sum <- fmt.Sprint("sum of even number = ", s1)
            waitGroup.Done()
        }(sum)
    
        // Waiting for all goroutines to exit
        waitGroup.Wait()
    
        // all goroutines are complete now close the sum channel
        close(sum)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么