英文:
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 < qtd; i++ {
go func(wg *sync.WaitGroup) {
defer wg.Done()
doRequest(http.MethodGet, "http://test.com", 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 < 5; i++ {
doRequest(http.MethodGet, "http://test.com", 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。
- 在每个goroutine中有5个doRequest()函数。
- 在一个goroutine中有5个doRequest()函数。
在第一种情况下,5个goroutine将并发运行。
在A Tour of Go中了解并发。
英文:
The go
keyword before a function will create a goroutine.
- 5 gouroutines, 1 doRequest() in per goroutine
- 1 gouroutine, 5 doRequest() in a goroutine
In the 1st case, 5 goroutines will run concurrently.
Check out concurrency in: A Tour of Go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论