From 5df5aa394a7a237a7e7cb666dd280b3ccef804fa Mon Sep 17 00:00:00 2001 From: Meutel Date: Sat, 8 Jul 2017 12:05:03 +0200 Subject: [PATCH] SHA directory with concurrency --- .gitignore | 1 + shadirconcurrent/main.go | 64 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 shadirconcurrent/main.go diff --git a/.gitignore b/.gitignore index aa04a47..d401de0 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ go-financial/go-financial my-fnv/my-fnv my-md5/my-md5 shadir/shadir +shadirconcurrent/shadirconcurrent diff --git a/shadirconcurrent/main.go b/shadirconcurrent/main.go new file mode 100644 index 0000000..c304b94 --- /dev/null +++ b/shadirconcurrent/main.go @@ -0,0 +1,64 @@ +package main + +import "fmt" +import "crypto/sha256" +import "io" +import "log" +import "os" +import "path/filepath" +import "sync/atomic" + +var chan_hash chan string +var running int32 + +func walk(path string, info os.FileInfo, err error) error { + if err != nil { + log.Fatalln(err) + return err + } + + if info.IsDir() { + return nil + } else { + atomic.AddInt32(&running, 1) + go hash(info.Name(), path) + } + return nil +} + +func hash(name string, path string) { + h, err := sha256File(path) + if err != nil { + log.Fatalln(err) + } + chan_hash <- fmt.Sprintf("SHA256 (%s) = %x", name, h) +} + +func sha256File(path string) ([]byte, error) { + f, err := os.Open(path) + if err != nil { + log.Fatalln(err) + return nil, err + } + defer f.Close() + h := sha256.New() + io.Copy(h, f) + return h.Sum(nil), nil +} + +func main() { + if len(os.Args) < 2 { + log.Fatalln("Usage shadir file") + } + chan_hash = make(chan string) + if err := filepath.Walk(os.Args[1], walk); err != nil { + panic(err) + } + for str := range chan_hash { + fmt.Println(str) + atomic.AddInt32(&running, -1) + if running <= 0 { + return + } + } +}