-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathnotification.go
80 lines (67 loc) · 1.95 KB
/
notification.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package watchdog
import "sync"
var (
gcNotifeeMutex sync.Mutex
gcNotifees []notifeeEntry
forcedGCNotifeeMutex sync.Mutex
forcedGCNotifees []notifeeEntry
)
// RegisterPostGCNotifee registers a function that is called every time a GC has happened,
// both GC runs triggered by the Go runtime and by watchdog.
// The unregister function returned can be used to unregister this notifee.
func RegisterPostGCNotifee(f func()) (unregister func()) {
gcNotifeeMutex.Lock()
defer gcNotifeeMutex.Unlock()
var id int
if len(gcNotifees) > 0 {
id = gcNotifees[len(gcNotifees)-1].id + 1
}
gcNotifees = append(gcNotifees, notifeeEntry{id: id, f: f})
return func() {
gcNotifeeMutex.Lock()
defer gcNotifeeMutex.Unlock()
for i, entry := range gcNotifees {
if entry.id == id {
gcNotifees = append(gcNotifees[:i], gcNotifees[i+1:]...)
}
}
}
}
func notifyGC() {
if NotifyGC != nil {
NotifyGC()
}
gcNotifeeMutex.Lock()
defer gcNotifeeMutex.Unlock()
for _, entry := range gcNotifees {
entry.f()
}
}
// RegisterPreGCNotifee registers a function that is called before watchdog triggers a GC run.
// It is ONLY called when watchdog triggers a GC run, not when the Go runtime triggers it.
// The unregister function returned can be used to unregister this notifee.
func RegisterPreGCNotifee(f func()) (unregister func()) {
forcedGCNotifeeMutex.Lock()
defer forcedGCNotifeeMutex.Unlock()
var id int
if len(forcedGCNotifees) > 0 {
id = forcedGCNotifees[len(forcedGCNotifees)-1].id + 1
}
forcedGCNotifees = append(forcedGCNotifees, notifeeEntry{id: id, f: f})
return func() {
forcedGCNotifeeMutex.Lock()
defer forcedGCNotifeeMutex.Unlock()
for i, entry := range forcedGCNotifees {
if entry.id == id {
forcedGCNotifees = append(forcedGCNotifees[:i], forcedGCNotifees[i+1:]...)
}
}
}
}
func notifyForcedGC() {
forcedGCNotifeeMutex.Lock()
defer forcedGCNotifeeMutex.Unlock()
for _, entry := range forcedGCNotifees {
entry.f()
}
}