go-examples/shadirconcurrent/main.go

66 lines
1.1 KiB
Go
Raw Normal View History

2017-07-08 10:05:03 +00:00
package main
import "fmt"
import "crypto/sha256"
import "io"
import "log"
import "os"
import "path/filepath"
2017-07-08 13:32:40 +00:00
import "sync"
2017-07-08 10:05:03 +00:00
func sha256File(path string) (string, error) {
2017-07-08 10:05:03 +00:00
f, err := os.Open(path)
if err != nil {
return "", err
2017-07-08 10:05:03 +00:00
}
defer f.Close()
h := sha256.New()
io.Copy(h, f)
return fmt.Sprintf("SHA256 (%s) = %x", path, h.Sum(nil)), nil
2017-07-08 13:32:40 +00:00
}
2017-07-08 15:32:21 +00:00
func runParallel(n uint, what func()) {
var wg sync.WaitGroup
for i := 0; i < int(n); i++ {
wg.Add(1)
what()
wg.Done()
}
wg.Wait()
}
2017-07-08 10:05:03 +00:00
func main() {
if len(os.Args) < 2 {
log.Fatalln("Usage shadir file")
}
2017-07-08 13:32:40 +00:00
chan_hash, chan_path := make(chan string), make(chan string)
2017-07-08 15:32:21 +00:00
go func() {
runParallel(100, func() { // 100 routines hashing
2017-07-08 14:50:08 +00:00
for path := range chan_path {
if h, err := sha256File(path); err != nil {
log.Print("Error "+path, err)
} else {
chan_hash <- h
}
}
2017-07-08 15:32:21 +00:00
})
2017-07-08 15:15:37 +00:00
close(chan_hash)
}()
2017-07-08 15:19:48 +00:00
go func() { // walk through files
2017-07-08 15:15:37 +00:00
filepath.Walk(os.Args[1], func(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() {
chan_path <- path
}
return err
})
close(chan_path)
}()
2017-07-08 15:15:37 +00:00
for h := range chan_hash {
fmt.Println(h)
2017-07-08 10:05:03 +00:00
}
}