dth981485742 2018-06-14 09:30
浏览 57
已采纳

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

I am going through the Tour of Go to refresh my memory, and am stumbling on the Equivalent Binary Trees exercise. I have written some code to traverse a binary tree that looks like it should work.

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)
    }
}

When I run the above code I'm getting the following error:

'\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

I am wondering why it is deadlocking? It looks like it does print out some garbage before this happens.

  • 写回答

2条回答 默认 最新

  • dpcwz210393 2018-06-14 09:42
    关注

    You must close the channel so range loop over it will terminate:

    func main() {
        ch := make(chan int, 10)
        go func() {
            Walk(tree.New(3), ch)
            close(ch)
        }()
        for v := range ch {
            fmt.Printf("%q", v)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件