有关goroutine性能的问题

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

Questions about goroutines performance

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言的新手,我想更多地了解goroutine。我将留下两个例子,并希望知道其中哪个更高效,以及为什么?

第一个例子:

func test() {
	var wg *sync.WaitGroup = new(sync.WaitGroup)

	qtd := 5

	wg.Add(qtd)
	for i := 0; i < qtd; i++ {
		go func(wg *sync.WaitGroup) {
			defer wg.Done()
			doRequest(http.MethodGet, "http://test.com", nil)

		}(wg)
	}
	wg.Wait()
}

第二个例子:

func test() {
	var wg *sync.WaitGroup = new(sync.WaitGroup)

	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		defer wg.Done()
		for i := 0; i < 5; i++ {
			doRequest(http.MethodGet, "http://test.com", nil)
		}
	}(wg)

	wg.Wait()
}

除了这两种方法,还有更好的方法吗?

如果没有,那么这两种方法中哪一种更高效?

英文:

I'm new to Golang, I would like to understand more about goroutine. I'll leave two examples and I wanted the opinion of which of the two is more performative and why?

func doRequest(method string, url string, body io.Reader) (*http.Response, error) {

	request, _ := http.NewRequest(method, url, body)
	
	response, err := c.httpClient.Do(request)
	request.Close = true
	c.httpClient.CloseIdleConnections()

	return response, err
}

first:

func test() {
	var wg *sync.WaitGroup = new(sync.WaitGroup)

	qtd := 5

	wg.Add(qtd)
	for i := 0; i &lt; qtd; i++ {
		go func(wg *sync.WaitGroup) {
			defer wg.Done()
			doRequest(http.MethodGet, &quot;http://test.com&quot;, nil)

		}(wg)
	}
	wg.Wait()
}

Second:

func test() {
	var wg *sync.WaitGroup = new(sync.WaitGroup)

	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		defer wg.Done()
		for i := 0; i &lt; 5; i++ {
			doRequest(http.MethodGet, &quot;http://test.com&quot;, nil)
		}
	}(wg)

	wg.Wait()
}

Is there a better way than these two?

If not, which of the two is more performant?

答案1

得分: 0

go关键字在函数前面会创建一个goroutine。

  1. 在每个goroutine中有5个doRequest()函数。
  2. 在一个goroutine中有5个doRequest()函数。

在第一种情况下,5个goroutine将并发运行。

A Tour of Go中了解并发。

英文:

The go keyword before a function will create a goroutine.

  1. 5 gouroutines, 1 doRequest() in per goroutine
  2. 1 gouroutine, 5 doRequest() in a goroutine

In the 1st case, 5 goroutines will run concurrently.

Check out concurrency in: A Tour of Go

huangapple
  • 本文由 发表于 2022年9月23日 20:24:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/73827703.html
匿名

发表评论

匿名网友

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

确定