英文:
What does select{} do?
问题
阅读《Go内存模型》时,我遇到了这段代码。
var limit = make(chan int, 3)
func main() {
for _, w := range work {
go func(w func()) {
limit <- 1
w()
<-limit
}(w)
}
select{}
}
我理解这个函数的作用是限制并发性,最多同时运行3个goroutine,但我不明白最后的select{}
是什么意思。我猜想这是一种方式,可以使main
函数保持活动状态,直到所有的goroutine都运行完毕,但我不能确定。
在空的select
中会发生什么?
英文:
Reading The Go Memory Model, I fell on this code snippet.
var limit = make(chan int, 3)
func main() {
for _, w := range work {
go func(w func()) {
limit <- 1
w()
<-limit
}(w)
}
select{}
}
I understand what this function is supposed to do – limit concurrency to 3 goroutines at any time – but I don't understand what the final select{}
does. I expect this is some way to keep main
alive until all goroutines have finished running, but I can't really say for sure.
What happens in an empty select
?
答案1
得分: 2
通常情况下,select{}
用于创建无限循环。
英文:
In generally, select{}
is used for infinite loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论