miro
miro

Reputation: 79

golang sync.WaitGroup never finishes

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

Upvotes: 1

Views: 3126

Answers (1)

apxp
apxp

Reputation: 5914

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.

Upvotes: 4

Related Questions