What does select{} do?

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

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 &lt;- 1
			w()
			&lt;-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.

huangapple
  • 本文由 发表于 2017年7月4日 23:42:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/44909935.html
匿名

发表评论

匿名网友

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

确定