douwei7471 2017-03-12 19:06
浏览 62
已采纳

golang sync.WaitGroup永远不会完成

the below code that get worker from channel and execute function "call", all routines finish and print that they are done but wait never finishes, i traced the counter of WaitGroup by making varible counter incresing when add to wg and decresing when done and it was zero at the end of for loop any help please

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)
", 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
", phase)
}
  • 写回答

1条回答 默认 最新

  • drv13270 2017-03-13 06:26
    关注

    The channel is blocking your goroutine. If you put some data into a unbuffered channel the goroutine waits until the receiver gets the the data from the channel. In your case your routine blocks at register <- worker and defer wg.Done() is never called, because the function is waiting.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动