forked from name5566/leaf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.go
72 lines (60 loc) · 1.01 KB
/
module.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
package module
import (
"github.com/name5566/leaf/conf"
"github.com/name5566/leaf/log"
"runtime"
"sync"
)
type Module interface {
OnInit()
OnDestroy()
Run(closeSig chan bool)
}
type module struct {
mi Module
closeSig chan bool
wg sync.WaitGroup
}
var mods []*module
func Register(mi Module) {
m := new(module)
m.mi = mi
m.closeSig = make(chan bool, 1)
mods = append(mods, m)
}
func Init() {
for i := 0; i < len(mods); i++ {
mods[i].mi.OnInit()
}
for i := 0; i < len(mods); i++ {
m := mods[i]
m.wg.Add(1)
go run(m)
}
}
func Destroy() {
for i := len(mods) - 1; i >= 0; i-- {
m := mods[i]
m.closeSig <- true
m.wg.Wait()
destroy(m)
}
}
func run(m *module) {
m.mi.Run(m.closeSig)
m.wg.Done()
}
func destroy(m *module) {
defer func() {
if r := recover(); r != nil {
if conf.LenStackBuf > 0 {
buf := make([]byte, conf.LenStackBuf)
l := runtime.Stack(buf, false)
log.Error("%v: %s", r, buf[:l])
} else {
log.Error("%v", r)
}
}
}()
m.mi.OnDestroy()
}