douqianrou9079 2014-04-28 16:27
浏览 70

在Go Tour等效二叉树上使用多个Goroutine

When attempting to solve tree walk portion of the Equivalent Binary Trees problem in the Go Tour, the obvious solution is to use recursion. Other solutions, such as a closure, are provided in answers to the general question on how to solve the problem.

My original thought was to use a Goroutine for each step of the walk. Isn't this a better, more Go-onic (what's the Go equivalent of Pythonic?) solution? The problem is I couldn't figure out how to either A) close the channel after the tree has been walked, or B) signal in some other way that the tree walk completed. An earlier example uses 2 channels, one for data and one for a quit signal. Passing a second channel doesn't fit with the problem definition, and the root issue of when the walk is finished is still present. Is there an elegant solution with a Goroutine for each walk step, or is recursion the best solution?

func Walk(t *tree.Tree, ch chan int) {
    if t != nil {
        go Walk(t.Left, ch)
        ch <- t.Value
        go Walk(t.Right, ch)
    }
    //Done with this node, how do I know when all are done?
}
  • 写回答

2条回答 默认 最新

  • dpjpo746884 2014-04-28 18:13
    关注

    Using a goroutine for each step of the walk will not work. Entirely apart from not knowing when you can close the channel (which I don't know of a good way to solve), you are not guaranteed to get the ordering you want. For example, the following code:

    go fmt.Println(1)
    go fmt.Println(2)
    go fmt.Println(3)
    

    Could print any of 123, 132, 213, 231, 312, or 321 depending on how the scheduler chooses to run those goroutines. This means that your Walk implementation is no longer going to give you the values in the correct order.

    Goroutines are only the right answer when there is actually something you want to do concurrently; given that the output to the channel has to be strictly ordered there is no concurrency to exploit in this problem.

    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助