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 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?