英文:
golang sync.WaitGroup never finishes
问题
以下是翻译好的代码:
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 // 输入数量(用于 reduce)或输出数量(用于 map)
switch phase {
case mapPhase:
ntasks = len(mapFiles)
n_other = nReduce
case reducePhase:
ntasks = nReduce
n_other = len(mapFiles)
}
fmt.Printf("调度:执行 %v 个任务 (%d I/Os)\n", ntasks, 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("调度:阶段 %v 完成\n", phase)
}
希望对你有帮助!
英文:
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)
}
答案1
得分: 3
该通道正在阻塞你的goroutine。如果你将一些数据放入一个无缓冲通道中,goroutine会等待接收者从通道中获取数据。在你的情况下,你的例程在register <- worker
处阻塞,而defer wg.Done()
从未被调用,因为该函数一直在等待。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论