Compare commits

...

2 Commits

Author SHA1 Message Date
a64a2dc434 add: signal退出带context 2022-01-19 12:26:38 +08:00
63f6788a12 add: waitgroup的用法 2022-01-19 12:08:37 +08:00
2 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*2)
waitForFinish(ctx, cancelFunc)
}
//waitForFinish 带context的退出
func waitForFinish(ctx context.Context, cancel context.CancelFunc) {
log.Println("waiting for finish...")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
select {
case <-ctx.Done():
log.Println("ctx done")
break
case <-sigChan:
log.Println("got termination signal,canceling execution...")
cancel()
}
}

View File

@ -0,0 +1,59 @@
package main
import (
"fmt"
"strconv"
"sync"
"time"
)
var wg sync.WaitGroup
// test1 不传递wg用匿名函数运行
func test1() {
wg.Add(2)
go func() {
defer wg.Done()
Info("task1")
}()
go func() {
defer wg.Done()
Info("task2")
}()
wg.Wait()
}
//test2 for循环并发
func test2() {
for i := 0; i <= 10; i++ {
wg.Add(1)
go func(a int) {
defer wg.Done()
Info("test" + strconv.Itoa(a+1))
}(i)
}
wg.Wait()
}
//test3 并发限速
func test3() {
limit := make(chan struct{}, 2)
for i := 0; i < 100; i++ {
wg.Add(1)
limit <- struct{}{}
go func(a int) {
defer func() {
wg.Done()
<-limit
}()
Info("test" + strconv.Itoa(i+1))
}(i)
}
wg.Wait()
}
func Info(name string) {
time.Sleep(time.Second)
fmt.Printf("this is a %v task...->%v\n", name, time.Now())
}