Compare commits
2 Commits
8cfb6c3d06
...
a64a2dc434
Author | SHA1 | Date | |
---|---|---|---|
a64a2dc434 | |||
63f6788a12 |
30
channel/signal-context/main.go
Normal file
30
channel/signal-context/main.go
Normal 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()
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
59
waitgroup/example1/main.go
Normal file
59
waitgroup/example1/main.go
Normal 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())
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user