```
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 了?
我在go语言圣经里看到这样一段代码,关于并发循环的,
```
// makeThumbnails6 makes thumbnails for each file received from the channel.
// It returns the number of bytes occupied by the files it creates.
func makeThumbnails6(filenames <-chan string) int64 {
sizes := make(chan int64)
var wg sync.WaitGroup // number of working goroutines
for f := range filenames {
wg.Add(1)
// worker
go func(f string) {
defer wg.Done()
thumb, err := thumbnail.ImageFile(f)
if err != nil {
log.Println(err)
return
}
info, _ := os.Stat(thumb) // OK to ignore error
sizes <- info.Size()
}(f)
}
// closer
go func() {
wg.Wait()
close(sizes)
}()
var total int64
for size := range sizes {
total += size
}
return total
}
```
[http://books.studygolang.com/gopl-zh/ch8/ch8-05.html](http://books.studygolang.com/gopl-zh/ch8/ch8-05.html)
#19
更多评论
问题的关键在于 main goroutine 提前退出了。
不论是那种代码,最好在 main 函数最后等待所有 goroutine 执行完成,方法很多了,可以 Sleep,可以 sync.WaitGroup 等等。
#1