0%

【Go】利用 signal + context 实现优雅退出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"time"
)

var wg sync.WaitGroup

func worker(name string, ctx context.Context, t time.Duration) {
fmt.Println(name, ": enter worker")
select {
case <-ctx.Done():
fmt.Println(name, ": worker context cancel, exit")
case <-time.After(t):
fmt.Println(name, ": worker process complete, exit")
}
wg.Done()
}

func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()

wg.Add(2)
go worker("worker1", ctx, time.Second*2)
go worker("worker2", ctx, time.Second*4)

wg.Wait()
fmt.Println("exit main")
}