golang sync.WaitGroup永远不会完成

huangapple go评论73阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;sync&quot;
)

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(&quot;Schedule: %v %v tasks (%d I/Os)\n&quot;, ntasks, phase, n_other)
	var wg sync.WaitGroup
	for i := 0; i &lt; ntasks; i++ {
		worker := &lt;-registerChan
		doTaskArg := DoTaskArgs{jobName, mapFiles[i], phase, i, n_other}
		wg.Add(1)
		go func() {
			defer wg.Done()

			done := call(worker, &quot;Worker.DoTask&quot;, doTaskArg, nil)
			if done {
				registerChan &lt;- worker
			} else {
				i = i - 1
			}

		}()
	}

	wg.Wait()

	fmt.Printf(&quot;Schedule: %v phase done\n&quot;, 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 &lt;- worker and defer wg.Done() is never called, because the function is waiting.

huangapple
  • 本文由 发表于 2017年3月13日 03:06:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/42751814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定