duanlaican1849 2015-03-04 14:38
浏览 41
已采纳

Go-tour解决方案中binarytrees_quit.go中退出通道的目的是什么?

I don't quite understand the purpose of quit channel variable in binarytrees_quit.go. Or, am I missing the important point here. I can understand that receiver can send value to quit to tell the go routine to return or exit. But I don't think that it's the case here. Is it just to make sure that Walk routines stick around till Same finishes the execution? Won't go routine stick around just because channels are not buffered. Even if this is the case, that does not make any sense. Please help me to understand.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doubeng1278 2015-03-04 14:43
    关注

    You can see that approached detailed in "Go for gophers - GopherCon closing keynote - 25 April 2014 - Andrew Gerrand "

    Stopping early
    Add a quit channel to the walker so we can stop it mid-stride.

    func walk(t *tree.Tree, ch chan int, quit chan struct{}) {
        if t.Left != nil {
            walk(t.Left, ch, quit)
        }
        select {
        case ch <- t.Value:
        // vvvvvvvvvvvv
        case <-quit:
            return
        }
        // ^^^^^^^^^^^^
        if t.Right != nil {
            walk(t.Right, ch, quit)
        }
    }
    

    Create a quit channel and pass it to each walker.
    By closing quit when the Same exits, any running walkers are terminated.

    func Same(t1, t2 *tree.Tree) bool {
        // vvvvvvvvvvvv
        quit := make(chan struct{})
        defer close(quit)
        w1, w2 := Walk(t1, quit), Walk(t2, quit)
        // ^^^^^^^^^^^^
        for {
            v1, ok1 := <-w1
            v2, ok2 := <-w2
            if v1 != v2 || ok1 != ok2 {
                return false
            }
            if !ok1 {
                return true
            }
        }
    }
    

    Andrew adds:

    Why not just kill the goroutines?

    Goroutines are invisible to Go code. They can't be killed or waited on.
    You have to build that yourself.

    There's a reason:

    As soon as Go code knows in which thread it runs you get thread-locality.
    Thread-locality defeats the concurrency model
    .

    • Channels are just values; they fit right into the type system.
    • Goroutines are invisible to Go code; this gives you concurrency anywhere.

    Less is more.

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

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理