我正在浏览 Tour of Go为了刷新我的内存,我偶然发现了等效二叉树练习。我已经编写了一些代码来遍历看起来应该可以工作的二叉树。
package main
import (
"golang.org/x/tour/tree"
"fmt"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t == nil {
return
}
ch <- t.Value
Walk(t.Left, ch)
Walk(t.Right, ch)
}
func main() {
ch := make(chan int, 10)
go Walk(tree.New(3), ch)
for v := range ch {
fmt.Printf("%q", v)
}
}
当我运行上面的代码时,出现以下错误:
'\x1e''\x0f''\t''\x03''\x06''\f''\x15''\x12''\x1b''\x18'fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/Users/james/src/local/go-sandbox/main.go:22 +0x115
Process finished with exit code 2
我想知道为什么会死锁?看起来它确实在发生这种情况之前打印出了一些垃圾。
最佳答案
您必须关闭 channel ,这样它的范围循环才会终止:
func main() {
ch := make(chan int, 10)
go func() {
Walk(tree.New(3), ch)
close(ch)
}()
for v := range ch {
fmt.Printf("%q", v)
}
}
关于go - 为什么这个树行走功能会死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50854132/