gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:05:27 24 4
gpt4 key购买 nike

我不太明白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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com