-
Notifications
You must be signed in to change notification settings - Fork 251
/
graceful.go
56 lines (43 loc) · 1.21 KB
/
graceful.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
50
51
52
53
54
55
56
package graceful
import "sync"
type GracefulTerminationFunc func(bool)
var (
// Mutex for access to other vars
m sync.Mutex
// True if a graceful termination has been requestd
terminationRequested bool
// pending callback for graceful termination (there can be only one)
callback GracefulTerminationFunc
)
// Return true if graceful termination has been requested
func TerminationRequested() bool {
m.Lock()
defer m.Unlock()
return terminationRequested
}
// Set up to call the given function (in a goroutine) when a termination
// request is received. Returns a function which, when called, will remove
// the callback. Only one callback can be installed at a time.
func OnTerminationRequest(f GracefulTerminationFunc) func() {
m.Lock()
defer m.Unlock()
if callback != nil {
panic("Cannot have two graceful termination callbacks")
}
callback = f
return func() {
m.Lock()
defer m.Unlock()
callback = nil
}
}
// A graceful termination has been requested. Set a flag so that no further
// tasks are claimed, and interrupt any running task if `finishTasks` is true
func Terminate(finishTasks bool) {
m.Lock()
defer m.Unlock()
terminationRequested = true
if callback != nil {
callback(finishTasks)
}
}