-
Notifications
You must be signed in to change notification settings - Fork 180
/
pool.go
70 lines (63 loc) · 1.26 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
package s3gof3r
import (
"container/list"
"time"
)
type qb struct {
when time.Time
s []byte
}
type bp struct {
makes int
get chan []byte
give chan []byte
quit chan struct{}
timeout time.Duration
bufsz int64
sizech chan int64
}
func bufferPool(bufsz int64) (sp *bp) {
sp = &bp{
get: make(chan []byte),
give: make(chan []byte),
quit: make(chan struct{}),
timeout: time.Minute,
sizech: make(chan int64),
}
go func() {
q := new(list.List)
for {
if q.Len() == 0 {
q.PushFront(qb{when: time.Now(), s: make([]byte, bufsz)})
sp.makes++
}
e := q.Front()
timeout := time.NewTimer(sp.timeout)
select {
case b := <-sp.give:
timeout.Stop()
q.PushFront(qb{when: time.Now(), s: b})
case sp.get <- e.Value.(qb).s:
timeout.Stop()
q.Remove(e)
case <-timeout.C:
// free unused slices older than timeout
e := q.Front()
for e != nil {
n := e.Next()
if time.Since(e.Value.(qb).when) > sp.timeout {
q.Remove(e)
e.Value = nil
}
e = n
}
case sz := <-sp.sizech: // update buffer size, free buffers
bufsz = sz
case <-sp.quit:
logger.debugPrintf("%d buffers of %d MB allocated", sp.makes, bufsz/(1*mb))
return
}
}
}()
return sp
}