dongweiben5229 2018-08-15 19:14
浏览 81
已采纳

可执行程序在空通道范围内抢先退出

I recently encountered a coding exercise which I solved in python in which I had to port an "algorithm". I don't know how it is called which is why I am describing it: Each new line was a description of the previous line by the amount of the same number printed in sequence and the associated number. Here is an example:

1
11
21
1211
111221
312211
etc

I started learning Go with its channels and concurrency features. So I came back to this exercise to try to solve it more efficiently in parallel with Go. This is what I got so far:

package main

func main() {
    channel := make(chan uint8)
    go treeCalcRoutine(channel, 0)
    channel <- 1
    close(channel) //defer is not an option in this case because the channel has 
    //to be closed before main exits
}

func treeCalcRoutine(in <-chan uint8, generation int) {
    if generation > 10 {
        return // return after 10 recursive iterations
    }
    out := make(chan uint8)
    defer close(out)
    num := uint8(1)
    previous := <-i
    go treeCalcRoutine(out, generation+1)
    for val := range in {
        switch {
        case val == previous:
            num++
        default:
            num = uint8(1)
            out <- num
            out <- val
        }
        previous = val
    }
    out <- num
    out <- previous
}

While trying to debug the program using Delve, I figured out the Program quits without an exception (and exit status 0) while trying to range over an empty/closed channel. I expected the program just to skip the for loop altogether in this case. I still want to solve this challenge myself so I would appreciate if someone could just point me in the right direction instead of producing a functioning solution. Moreover, please point out any other issues/cases which could be done better (like the generation limit).

EDIT: Since people asking me to post the error: There is no error at all for some reason. The program just exits once it reaches the for loop.

  • 写回答

1条回答 默认 最新

  • douliaodun9153 2018-08-15 19:44
    关注

    So the issue was not actually that the for loop was exiting when it was encountering the closed channel but the main routine exited at that exact time which caused every other goroutine to terminate as well. I was advised to use waitgroups in this case.

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

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)