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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用