Go goroutines没有被执行

时间:2016-10-05 16:00:01

标签: go goroutine

我试图在这里实现某种多线程处理。

func (m *Map) Parse(mapData Node) error {
    wg := &sync.WaitGroup{}
    for _, node := range mapData.child {
        wg.Add(1)
        go parseChild(node, m, wg)
    }
    wg.Wait()
    close(errors)
    return nil
}

func parseChild(node Node, m *Map, wg *sync.WaitGroup) {
    defer wg.Done()
    var nodeType uint8
    if err := binary.Read(node.data, binary.LittleEndian, &nodeType); err != nil {
        errors <- err
    }
    if nodeType == OTBMNodeTowns {
        for _, town := range node.child {
            var nodeType uint8

            if err := binary.Read(town.data, binary.LittleEndian, &nodeType); err != nil {
                errors <- err
                return
            }
            if nodeType != OTBMNodeTown {
                errors <- fmt.Errorf("Parsing map towns: expected %v got %v", OTBMNodeTown, nodeType)
                return
            }
            currentTown := Town{}
            if err := binary.Read(town.data, binary.LittleEndian, &currentTown.ID); err != nil {
                errors <- err
                return
            } else if currentTown.Name, err = town.ReadString(); err != nil {
                errors <- err
                return
            } else if currentTown.TemplePosition, err = town.ReadPosition(); err != nil {
                errors <- err
                return
            }
            m.Towns = append(m.Towns, currentTown)
            errors <- fmt.Errorf("This should be called: %v, nodeType)
            return
        }
    }
}

但我的goroutine从未向错误频道发送任何内容。似乎是主线程没有等待goroutines甚至完成

我不知道我在这里缺少什么。我等待所有例程完成使用wg.Wait但似乎没有工作,因为我认为它应该

是的。切片填充至少3个结果。这是错误的通道

var (
    errors = make(chan error, 0)
)

func init() {
    go errChannel()
}

func errChannel() {
    for {
        select {
        case err := <-errors:
            log.Println(err)
        }
    }
}

0 个答案:

没有答案