大家来解惑--这段代码有啥问题?

javasgl · · 2829 次点击
我在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
更多评论
polaris
社区,需要你我一同完善!
问题的关键在于 main goroutine 提前退出了。 不论是那种代码,最好在 main 函数最后等待所有 goroutine 执行完成,方法很多了,可以 Sleep,可以 sync.WaitGroup 等等。
#1
但是我只仅仅调换了下 sleep 和 print 语句的先后顺序,就能打印到 99 了。
#2