add examples about goroutine and wait group

This commit is contained in:
oscarzhou 2022-01-24 10:28:01 +13:00
parent f16bfef103
commit f0c2621469
2 changed files with 95 additions and 0 deletions

28
1-echo-text/main.go Normal file
View File

@ -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)
}

67
2-compress-file/main.go Normal file
View File

@ -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
}