Skip to content

Instantly share code, notes, and snippets.

@jimhorng
Last active April 20, 2016 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimhorng/b8582c3794227a0ed5033eb6e0d2b2c3 to your computer and use it in GitHub Desktop.
Save jimhorng/b8582c3794227a0ed5033eb6e0d2b2c3 to your computer and use it in GitHub Desktop.
golang goroutine example
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() # location 1
close(sizes) # location 1
}()
wg.Wait() # location 2
close(sizes) # location 2
var total int64
for size := range sizes {
total += size
}
return total
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment