这是参考 The Go Programming Language - Chapter 8 p.238 中的以下代码,从该链接下面复制
// 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
fmt.Println(info.Size())
sizes <- info.Size()
}(f)
}
// closer
go func() {
wg.Wait()
close(sizes)
}()
var total int64
for size := range sizes {
total += size
}
return total
}
为什么我们需要将 closer 放在 goroutine 中?为什么下面不能工作?
// closer
// go func() {
fmt.Println("waiting for reset")
wg.Wait()
fmt.Println("closing sizes")
close(sizes)
// }()
如果我尝试运行上面的代码,它会给出:
等待重置
3547
2793
致命错误:所有 goroutines 都睡着了 - 死锁!
为什么上面会出现死锁?fyi,在调用的方法中makeThumbnail6我确实关闭了filenames频道
手掌心
aluckdog
哔哔one
相关分类