Skip to content

Commit f335d42

Browse files
authored
CLOUDP-125763: Fix race condition for sighandle (#1300)
1 parent 2564835 commit f335d42

File tree

1 file changed

+32
-20
lines changed

1 file changed

+32
-20
lines changed

internal/sighandle/sighandle.go

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,44 +15,56 @@
1515
package sighandle
1616

1717
import (
18+
"context"
1819
"os"
1920
"os/signal"
2021
)
2122

2223
type handler struct {
23-
sig []os.Signal
24-
f func(os.Signal)
25-
c chan os.Signal
26-
notified bool
24+
sig []os.Signal
25+
handlerFunc func(os.Signal)
26+
sigChannel chan os.Signal
27+
cancel func()
2728
}
2829

29-
func (h *handler) routine() {
30-
h.f(<-h.c)
30+
func (h *handler) routine(ctx context.Context) {
31+
select {
32+
case <-ctx.Done():
33+
// cancel this goroutine
34+
case s := <-h.sigChannel:
35+
h.handlerFunc(s)
36+
}
3137
}
3238

33-
func (h *handler) notify() {
34-
if h.notified {
35-
h.reset()
36-
}
37-
h.notified = true
38-
h.c = make(chan os.Signal, 1)
39-
go h.routine()
40-
signal.Notify(h.c, h.sig...)
39+
func (h *handler) notify(ctx context.Context) {
40+
go h.routine(ctx)
41+
signal.Notify(h.sigChannel, h.sig...)
4142
}
4243

4344
func (h *handler) reset() {
4445
signal.Reset(h.sig...)
45-
h.notified = false
46+
h.cancel()
4647
}
4748

48-
var std = &handler{}
49+
var std *handler
4950

5051
func Notify(f func(os.Signal), sig ...os.Signal) {
51-
std.f = f
52-
std.sig = sig
53-
std.notify()
52+
Reset()
53+
54+
ctx, cancel := context.WithCancel(context.Background())
55+
56+
std = &handler{
57+
handlerFunc: f,
58+
sig: sig,
59+
sigChannel: make(chan os.Signal, 1),
60+
cancel: cancel,
61+
}
62+
std.notify(ctx)
5463
}
5564

5665
func Reset() {
57-
std.reset()
66+
if std != nil {
67+
std.reset()
68+
std = nil
69+
}
5870
}

0 commit comments

Comments
 (0)