doushui3216 2014-04-26 21:38
浏览 23
已采纳

渠道僵局

I'm building an asynchronous Btree in Go with channels, but I'm getting the error fatal error: all goroutines are asleep - deadlock! I don't know why 'cause I'm getting the values from the channel in a for loop with a buffered channel.

type Obj interface {
    Compare(node Obj) int
}

type Tree struct {
    Item        Obj
    Rigth, Left *Tree
    height      int16
}

func NewTree() *Tree {
    return &Tree{Item: nil, Rigth: nil, Left: nil, height: 0}
}

func InOrder(t *Tree, chTree chan Obj) {
    if t != nil {
        InOrder(t.Left, chTree)
        chTree <- t.Item
        InOrder(t.Rigth, chTree)
    }
}

// == testing ==

func TestInOrder(t *testing.T) {
    tree := NewTree()
    nums := []int{9, 7, 2, 4, 6, 10, 1, 5, 8, 3}
    for i := 0; i < len(nums); i++ {
        tree.Insert(ObjInt{nums[i]})
    }
    result := make(chan Obj, 10)
    go InOrder(tree, result)
    var previous Obj
    for obj := range result {
        fmt.Println(obj)
        if previous == nil {
            previous = obj
            continue
        }
        assertTrue(previous.Compare(obj) == -1, t,
            "Previous obj should be smaller than current object")
        previous = obj
    }
}

Output:

1
2
3
4
5
6
7
8
9
10

fatal error: all goroutines are asleep - deadlock!
  • 写回答

1条回答 默认 最新

  • doucha5080 2014-04-26 22:13
    关注

    You're not closing the channel. You'll notice that it's actually printing correctly, then freaking out.

    In a range over a channel, like this:

    for obj := range result {
         //...
    }
    

    The loop will only exit if you call close(result). In this case it's a bit tricky because of the recursive nature. Ultimately I'd recommend wrapping the call to InOrder like so:

    func InOrder(t *Tree, chTree chan obj) {
        inOrder(t, chTree)
        close(chTree)
    }
    
    func inOrder(t *Tree, chTree chan Obj) {
        if t != nil {
            inOrder(t.Left, chTree)
            chTree <- t.Item
            inOrder(t.Rigth, chTree)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程