- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我不太明白binarytrees_quit.go中quit channel 变量的用途。或者,我是否错过了这里的重点。我可以理解接收器可以发送值来退出以告诉 go 例程返回或退出。但我不认为这里是这种情况。是否只是为了确保 Walk 例程一直保留到 Same 完成执行?不会仅仅因为 channel 没有缓冲就例行公事。即使是这样,那也没有任何意义。请帮助我理解。
提前致谢!
最佳答案
你可以在“Go for gophers - GopherCon closing keynote - 25 April 2014 - Andrew Gerrand ”中看到详细的方法
Stopping early
Add aquit
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 closingquit
when theSame
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/
我不太明白binarytrees_quit.go中quit channel 变量的用途。或者,我是否错过了这里的重点。我可以理解接收器可以发送值来退出以告诉 go 例程返回或退出。但我不认为这里是这种
我是一名优秀的程序员,十分优秀!