golang sync.WaitGroup永远不会完成

时间:2017-03-12 19:06:24

标签: go

下面的代码让工作人员从频道和执行函数"调用",所有例程完成并打印它们已完成但等待永远不会完成, 我跟踪了WaitGroup的计数器,通过在添加到wg时使变量计数器为incresing并在完成时进行decresing并且在for循环结束时为零 任何帮助,请

package mapreduce

import (
    "fmt"
    "sync"
)

func schedule(jobName string, mapFiles []string, nReduce int, phase jobPhase, registerChan chan string) {
    var ntasks int
    var n_other int // number of inputs (for reduce) or outputs (for map)
    switch phase {
    case mapPhase:
        ntasks = len(mapFiles)
        n_other = nReduce
    case reducePhase:
        ntasks = nReduce
        n_other = len(mapFiles)

    }

    fmt.Printf("Schedule: %v %v tasks (%d I/Os)\n", ntasks, phase, n_other)
    var wg sync.WaitGroup
    for i := 0; i < ntasks; i++ {
        worker := <-registerChan
        doTaskArg := DoTaskArgs{jobName, mapFiles[i], phase, i, n_other}
        wg.Add(1)
        go func() {
            defer wg.Done()

            done := call(worker, "Worker.DoTask", doTaskArg, nil)
            if done {
                registerChan <- worker
            } else {
                i = i - 1
            }

        }()
    }

    wg.Wait()

    fmt.Printf("Schedule: %v phase done\n", phase)
}

1 个答案:

答案 0 :(得分:2)

该频道阻止了您的goroutine。如果您将一些数据放入无缓冲的通道,则goroutine会等待接收器从通道获取数据。在您的情况下,永远不会调用register <- workerdefer wg.Done()处的例程块,因为函数正在等待。