```
package main
import (
"fmt"
"time"
)
func main() {
limiter := make(chan bool, 10)
for i := 0; i < 100; i++ {
limiter <- true
go download(i, limiter)
}
}
func download(index int, limiter chan bool) {
time.Sleep(1 * time.Second)
fmt.Println("start to download :", index)
<-limiter
}
```
上面这段代码执行结果为什么最大打印值直到 89 ?
当把
```
time.Sleep(1 * time.Second)
fmt.Println("start to download :", index)
```
两行上下调换之后,变成以下的代码:
```
fmt.Println("start to download :", index)
time.Sleep(1 * time.Second)
```
就能正常打印到 99 了?
有个小问题昂, 在所有worker goroutine们结束之后, 不是应该手动关闭limiter channel吗?
```
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := &sync.WaitGroup{}
limiter := make(chan bool, 10)
for i := 0; i < 100; i++ {
wg.Add(1)
limiter <- true
go download(i, limiter, wg)
}
wg.Wait()
close(limiter) //这里
}
func download(index int, limiter chan bool, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("start to download :", index)
time.Sleep(1 * time.Second)
<-limiter
}
```
#16
更多评论
问题的关键在于 main goroutine 提前退出了。
不论是那种代码,最好在 main 函数最后等待所有 goroutine 执行完成,方法很多了,可以 Sleep,可以 sync.WaitGroup 等等。
#1