go - go-tour 解决方案中 binarytrees_quit.go 中的 quit channel 的目的是什么?

标签 go

我不太明白binarytrees_quit.go中quit channel 变量的用途。或者,我是否错过了这里的重点。我可以理解接收器可以发送值来退出以告诉 go 例程返回或退出。但我不认为这里是这种情况。是否只是为了确保 Walk 例程一直保留到 Same 完成执行?不会仅仅因为 channel 没有缓冲就例行公事。即使是这样,那也没有任何意义。请帮助我理解。

提前致谢!

最佳答案

你可以在“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
        }
    }
}

安德鲁补充说:

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.

关于go - go-tour 解决方案中 binarytrees_quit.go 中的 quit channel 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28857190/

相关文章:

JSON 键可以是字符串或对象

go - 有没有更好的方法来观看 imap 邮箱更新?

string - 去整理一片 rune ?

go - 使用更新的 CommonName 重新生成新的 x509 证书

go - 如何创建带有“New”前缀混淆的结构

Go 接口(interface)在方法之间强制执行相同的参数类型(但可以是任何类型)

xml - 使用 Go 并行读取多个 URL

go - 如何使用FabCar计算平均价格

go - 为什么没有填充此 HTTP 请求的响应字段?

Golang 命令在终端中工作但不与 exec 包一起工作