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

图片转代码服务由CSDN问答提供 功能建议

我正在使用一个示例程序使用goroutine在1至100之间打印奇数和偶数之和。

您可以找到我的代码

此处

输出

 偶数之和= 2550 
奇数之和= 2500  
致命错误:所有goroutine都在睡眠中-死锁!
 
goroutine 1 [chan接收]:
main.print(0x434100,0x11db7c)
 /tmp/sandbox052575152/main.go:18 + 0xc0 
main.main()  
 /tmp/sandbox052575152/main.go:14 + 0x120 
   
 
 

该代码有效,但出现死锁。 我不确定我的代码有什么问题< / p>

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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)
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题