频道死锁

时间:2014-04-26 21:38:12

标签: go deadlock goroutine

我正在使用频道在Go中构建一个异步Btree,但我收到错误fatal error: all goroutines are asleep - deadlock!我不知道为什么'因为我在for循环中获取了来自通道的值缓冲频道。

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

输出:

1
2
3
4
5
6
7
8
9
10

fatal error: all goroutines are asleep - deadlock!

1 个答案:

答案 0 :(得分:3)

您没有关闭频道。您会注意到它实际打印正确,然后吓坏了。

通过频道range,就像这样:

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

只有在您拨打close(result)时,循环才会退出。在这种情况下,由于递归性质,它有点棘手。最后,我建议将呼叫包裹到InOrder,如下所示:

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)
    }
}
相关问题