Compare commits
No commits in common. "a64a2dc434b37cc09ab45eccca01c84d0f17bd6b" and "8cfb6c3d06544e1620a3903b84f8ac0f0284ebfd" have entirely different histories.
a64a2dc434
...
8cfb6c3d06
@ -1,30 +0,0 @@
|
|||||||
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()
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,59 +0,0 @@
|
|||||||
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())
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user