forked from ginuerzh/gost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
108 lines (92 loc) · 1.53 KB
/
pool.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// pool for buffer
package main
import (
"container/list"
//"log"
"time"
)
type poolItem struct {
when time.Time
item interface{}
}
type pool struct {
quque *list.List
takeChan, putChan chan interface{}
age time.Duration
max int
}
func (p *pool) run() {
for {
if p.size() == 0 {
select {
case b := <-p.putChan:
p.put(b)
}
continue
}
i := p.quque.Front()
timeout := time.NewTimer(p.age)
select {
case b := <-p.putChan:
timeout.Stop()
p.put(b)
case p.takeChan <- i.Value.(*poolItem).item:
timeout.Stop()
p.quque.Remove(i)
case <-timeout.C:
i = p.quque.Back()
for i != nil {
if time.Since(i.Value.(*poolItem).when) < p.age {
break
}
e := i.Prev()
p.quque.Remove(i)
i = e
}
}
}
}
func (p *pool) size() int {
return p.quque.Len()
}
func (p *pool) put(v interface{}) {
if p.size() < p.max {
p.quque.PushFront(&poolItem{when: time.Now(), item: v})
return
}
}
type MemPool struct {
pool
bs int
}
func NewMemPool(bs int, age time.Duration, max int) *MemPool {
if bs <= 0 {
bs = 8192
}
if age == 0 {
age = 1 * time.Minute
}
p := &MemPool{
pool: pool{
quque: list.New(),
takeChan: make(chan interface{}),
putChan: make(chan interface{}),
age: age,
max: max,
},
bs: bs,
}
go p.run()
return p
}
func (p *MemPool) Take() []byte {
select {
case v := <-p.takeChan:
return v.([]byte)
default:
return make([]byte, p.bs)
}
}
func (p *MemPool) Put(b []byte) {
p.putChan <- b
}