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 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析