From f0c2621469039f0949021d7a3933fb30134104a6 Mon Sep 17 00:00:00 2001 From: oscarzhou Date: Mon, 24 Jan 2022 10:28:01 +1300 Subject: [PATCH] add examples about goroutine and wait group --- 1-echo-text/main.go | 28 +++++++++++++++++ 2-compress-file/main.go | 67 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 1-echo-text/main.go create mode 100644 2-compress-file/main.go diff --git a/1-echo-text/main.go b/1-echo-text/main.go new file mode 100644 index 0000000..b0f92dd --- /dev/null +++ b/1-echo-text/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "io" + "os" + "time" +) + +/* + @Ref: https://livebook.manning.com/book/go-in-practice/chapter-3/65 + `os.Stdin` and `os.Stdout` will be used as the system input and output. It's great. + + +*/ + +func main() { + go echo(os.Stdin, os.Stdout) + + time.Sleep(30 * time.Second) + + fmt.Println("Time out.") + os.Exit(0) +} + +func echo(in io.Reader, out io.Writer) { + io.Copy(out, in) +} diff --git a/2-compress-file/main.go b/2-compress-file/main.go new file mode 100644 index 0000000..d8704ae --- /dev/null +++ b/2-compress-file/main.go @@ -0,0 +1,67 @@ +package main + +import ( + "compress/gzip" + "fmt" + "io" + "os" + "sync" +) + +/* + @Ref: https://livebook.manning.com/book/go-in-practice/chapter-3/65 + 1. Practice gzip compress + 2. How to use wait group + 3. os.Args[1:] can stream in multiple files to the program without writing a walk function. Command: go run main.go ./testdata/* + +*/ +func main() { + + // Single thread + // for _, file := range os.Args[1:] { + + // err := compress(file) + // if err != nil { + // os.Exit(0) + // } + // } + + // Multi threads + wg := sync.WaitGroup{} + var ( + i int + file string + ) + for i, file = range os.Args[1:] { + wg.Add(1) + go func(filename string) { + compress(filename) + wg.Done() + }(file) + } + + wg.Wait() + fmt.Printf("Compressed %d files\n", i+1) +} + +func compress(filename string) error { + in, err := os.Open(filename) + if err != nil { + return err + } + + defer in.Close() + + out, err := os.Create(filename + ".gz") + if err != nil { + return err + } + + defer out.Close() + + gzout := gzip.NewWriter(out) + _, err = io.Copy(gzout, in) + gzout.Close() + + return err +}