go - 为什么这个树行走功能会死锁?

标签 go tree

我正在浏览 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/

相关文章:

c - 具有 2 种不同 key 类型和最小冗余码的树数据结构

json - 如何转义字符串中的字符(JSON 格式)

http - 获取 "127.0.0.1 can' t 分配请求的地址”- http.Client

GO 中的 XML 解码

c# - 从按树顺序排序的树创建平面列表

javascript - 将树数据结构保存到文本文件 JavaScript

algorithm - 尝试理解四叉树概念并将其应用于存储图像的着色信息

javascript - d3 力有向图向下力模拟

go - 如何检索嵌套的 map 值

go - 类似 Golang 变量的命名约定