From 8b70410d5848258cc2e86e7eec0504b46b48f27d Mon Sep 17 00:00:00 2001 From: Greg Date: Thu, 2 Apr 2020 14:06:11 -0400 Subject: [PATCH] Add concurrency. --- main.go | 52 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/main.go b/main.go index c924014..80d9afd 100644 --- a/main.go +++ b/main.go @@ -6,41 +6,53 @@ import ( "fmt" "io" "os" + "sync" "github.com/zeebo/blake3" ) var ( help = flag.Bool("h", false, "Prints help information") - length = flag.Int("l", 32, "The number of output bytes, prior to hex encoding (default 32)") + length = flag.Int("l", 32, "The number of output bytes, prior to hex encoding") + par = flag.Int("p", 4, "The maximum concurrency") ) func main() { flag.Parse() - if *help || len(flag.Args()) == 0 { + if *help || len(flag.Args()) == 0 || *par < 1 { flag.Usage() os.Exit(0) } - buf := [65536]byte{} + q := make(chan struct{}, *par) + wg := &sync.WaitGroup{} + for _, name := range flag.Args() { - file, err := os.Open(name) - if err != nil { - panic(err) - } - hasher := blake3.NewSized(*length) - for { - n, err := file.Read(buf[:]) - hasher.Write(buf[:n]) - if err == io.EOF { - break - } else if err != nil { + q <- struct{}{} + wg.Add(1) + go func(name string) { + buf := [65536]byte{} + file, err := os.Open(name) + if err != nil { panic(err) } - } - file.Close() - hash := hasher.Sum([]byte{}) - fmt.Print(hex.EncodeToString(hash)) - fmt.Print(" ") - fmt.Println(name) + hasher := blake3.NewSized(*length) + for { + n, err := file.Read(buf[:]) + hasher.Write(buf[:n]) + if err == io.EOF { + break + } else if err != nil { + panic(err) + } + } + file.Close() + hash := hasher.Sum([]byte{}) + fmt.Print(hex.EncodeToString(hash)) + fmt.Print(" ") + fmt.Println(name) + <- q + wg.Done() + }(name) } + wg.Wait() }