/
mistake_ctx_order.go
49 lines (44 loc) · 1.22 KB
/
mistake_ctx_order.go
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"context"
"fmt"
"sync"
"syscall"
"github.com/Code-Hex/sigctx"
)
// This is a complicated case using `sigctx.WithSignals`
// and `sigctx.WithCancelSignals` together.
// If you mistake the order of using `sigctx.WithSignals` and
// `sigctx.WithCancelSignals`, You will suffer by context.
func main() {
// First, Create a context to notify all goroutines.
signalctx := sigctx.WithSignals(context.Background(), syscall.SIGINT, syscall.SIGTERM)
// Second, Wrap the signal context to cancel all goroutines.
cancelctx := sigctx.WithCancelSignals(signalctx, syscall.SIGHUP)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
// Since it is the context to receive,
// You should pass the signal context as an argument.
case <-sigctx.Recv(signalctx):
// `sigctx.Signal(signalctx)` is also the same reason.
signal, err := sigctx.Signal(signalctx)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(signal.String())
}
// `cancelctx.Done()` Because of the context to cancel by signal.
case <-cancelctx.Done():
fmt.Println(cancelctx.Err())
return
}
}
}()
}
wg.Wait()
}