英文:
GO - subroutine behaviour in a for loop
问题
我对go语言中for循环中子程序的行为有一些疑问。
根据我的理解,当我们有一个for循环:
for key := range Map {
go subroutine(Map[key])
}
其中Map有3个(key,Value)对。
所以我的理解是,*subroutine()函数将并发地使用所有的Map[Key]*值,也就是subroutine(Map[key1])、subroutine(Map[key2])和subroutine(Map[key3])将同时运行?
我的理解对于for循环中的并发子程序正确吗?
谢谢!
英文:
I'm having some doubts on my understanding of the behaviour of a go subroutine in a for loop.
From what I understand, when we have a for loop:
for key := range Map {
go subroutine(Map[key])
}
Where Map has, let's say 3 (key,Value) pairs.
So my understanding is that the subroutine() function will run concurrently using all the Map[Key] values ie subroutine(Map[key1]),subroutine(Map[key2]) and subroutine(Map[key3]) will all run concurrently ?
Is my understanding of concurrent subroutines in a for loop correct?
Thanks!
答案1
得分: 2
是的。请记住,在程序结束之前,您仍然需要保持主 goroutine 存活,以便这些操作能够完成。您可以使用类似 sync.WaitGroup 的方法:
wg := new(sync.WaitGroup)
for key := range Map {
wg.Add(1)
go func() {
subroutine(Map[key])
wg.Done()
}()
}
wg.Wait()
或者,如果您的主例程中有类似服务器循环的操作,您可能根本不需要使用 sync.WaitGroup,因为您的程序将在外部发送相关信号之前不会结束。
希望对您有所帮助。
英文:
Yes. Please remember that you will still need the main goroutine alive for these to finish before the program ends. You can use something like sync.WaitGroup:
wg := new(sync.WaitGroup)
for key := range Map {
wg.Add(1)
go func() {
subroutine(Map[key])
wg.Done()
}
}
wg.Wait()
Or if you have something like a server loop going on in the main routine you may not need that at all since your program won't finish until a relevant signal is externally sent to it.
Hope that helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论