/
recycler_action.go
68 lines (59 loc) · 965 Bytes
/
recycler_action.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
package netlib
import "sync"
var ap = NewActionPool(1024)
func AllocAction() *action {
return ap.Get()
}
func FreeAction(a *action) {
ap.Give(a)
}
type ActionPool struct {
free *action
lock *sync.Mutex
num int
allocNum int
remainNum int
}
func NewActionPool(num int) *ActionPool {
ap := &ActionPool{
lock: new(sync.Mutex),
num: num,
}
return ap
}
func (ap *ActionPool) grow() {
var (
i int
a *action
as = make([]action, ap.num)
)
ap.free = &(as[0])
a = ap.free
for i = 1; i < ap.num; i++ {
a.next = &(as[i])
a = a.next
}
a.next = nil
ap.allocNum += ap.num
ap.remainNum += ap.num
return
}
func (ap *ActionPool) Get() (a *action) {
ap.lock.Lock()
if a = ap.free; a == nil {
ap.grow()
a = ap.free
}
ap.free = a.next
a.next = nil
ap.remainNum--
ap.lock.Unlock()
return
}
func (ap *ActionPool) Give(a *action) {
ap.lock.Lock()
a.next = ap.free
ap.free = a
ap.remainNum++
ap.lock.Unlock()
}