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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵