如何等待一组 goroutine?

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

How to wait for a group of goroutines?

问题

让我们假设我想要启动一组 goroutine,然后等待它们全部完成(例如返回结果)。
我可以想到一些基于通道的解决方案(例如创建一个通道并监听它,计算接收到的消息数量,这些消息应该由每个 goroutine 发送,并在接收到相应数量的消息后退出),但也许有一种更优雅/高效的解决方案,因为这种情况似乎非常常见。

英文:

let's say I want to start a group of goroutines and than wait for all of them to finish (e.g. return).
I can think of some channel-based solution (e.g. create a channel and listen to it counting received messages which shall be sent by each of goroutines and quiting after receive corresponding number of msgs) but maybe there's a more elegant/efficient solution because this case seems very common.

答案1

得分: 6

是的,你想要一个*sync.WaitGroup,你可以通过在每个任务开始之前调用waitGroup.Add(1),在任务完成时调用waitGroup.Done(),以及在启动所有任务并等待它们全部完成时调用waitGroup.Wait()来使用它,像这样

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	wg := new(sync.WaitGroup)
	for i := 1; i < 3; i++ {
		wg.Add(1)
		go func(i int) { // ensures each run gets distinct i
			fmt.Println("Sleeping", i, "seconds")
			time.Sleep(time.Duration(i) * time.Second)
			fmt.Println("Slept", i, "seconds")
			wg.Done()
		}(i)
	}
	wg.Wait()
	fmt.Println("All done")
}
英文:

Yes; you want a *sync.WaitGroup, which you can use by calling waitGroup.Add(1) before starting each task, waitGroup.Done() when it finishes, and waitGroup.Wait() once you have started everything and want to wait for it all to finish, like this:

package main

import (
	&quot;fmt&quot;
	&quot;sync&quot;
	&quot;time&quot;
)

func main() {
	wg := new(sync.WaitGroup)
	for i := 1; i &lt; 3; i++ {
		wg.Add(1)
		go func(i int) { // ensures each run gets distinct i
			fmt.Println(&quot;Sleeping&quot;, i, &quot;seconds&quot;)
			time.Sleep(time.Duration(i) * time.Second)
			fmt.Println(&quot;Slept&quot;, i, &quot;seconds&quot;)
			wg.Done()
		}(i)
	}
	wg.Wait()
	fmt.Println(&quot;All done&quot;)
}

huangapple
  • 本文由 发表于 2015年12月30日 02:59:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/34517289.html
匿名

发表评论

匿名网友

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

确定