Skip to content

Instantly share code, notes, and snippets.

@simonjefford
Last active August 29, 2015 14:06
Show Gist options
  • Save simonjefford/5d8f7cf1564b0512901d to your computer and use it in GitHub Desktop.
Save simonjefford/5d8f7cf1564b0512901d to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"image"
_ "image/jpeg"
"os"
"os/exec"
"runtime"
"sync"
)
func checkFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
cfg, _, err := image.DecodeConfig(f)
if cfg.Width > 2500 {
fmt.Printf("%s: %d x %d\n", path, cfg.Height, cfg.Width)
}
return nil
}
type photoChecker struct {
done chan struct{}
wg sync.WaitGroup
fileCh chan string
}
func newPhotoChecker() *photoChecker {
return &photoChecker{
done: make(chan struct{}),
fileCh: make(chan string, 1),
}
}
func (p *photoChecker) run(numRoutines int) {
for i := 0; i < numRoutines; i++ {
p.wg.Add(1)
go func() {
run := true
for run {
select {
case file := <-p.fileCh: // get the next file name from the queue
err := checkFile(file)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
case <-p.done: // will exec when the channel is closed
run = false
}
}
p.wg.Done()
}()
}
}
func (p *photoChecker) addFile(path string) {
p.fileCh <- path
}
func (p *photoChecker) stopAndWait() {
close(p.done) // reading from a closed channel immediately yields nil, forever
p.wg.Wait()
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
cmd := exec.Command("find", ".", "-name", "*.jpg")
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := cmd.Start(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
checker := newPhotoChecker()
checker.run(runtime.NumCPU())
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
checker.addFile(scanner.Text())
}
err = scanner.Err()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
checker.stopAndWait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment