forked from miekg/dns
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpool.go
61 lines (50 loc) · 1.14 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
// Copyright 2011 Miek Gieben. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dns
// Inspired copied from:
// http://blog.cloudflare.com/recycling-memory-buffers-in-go
// ... carries no license ...
import (
"container/list"
"time"
)
func mkBuf(size int) []byte { return make([]byte, size) }
type queued struct {
when time.Time
buf []byte
}
func pool(size, bufsize int) (get, give chan []byte) {
get = make(chan []byte, bufsize)
give = make(chan []byte, bufsize)
go func() {
q := new(list.List)
for {
e := q.Front()
if e == nil {
q.PushFront(queued{when: time.Now(), buf: mkBuf(size)})
e = q.Front()
}
timeout := time.NewTimer(time.Minute)
select {
case b := <-give:
timeout.Stop()
q.PushFront(queued{when: time.Now(), buf: b})
case get <- e.Value.(queued).buf:
timeout.Stop()
q.Remove(e)
case <-timeout.C:
e := q.Front()
for e != nil {
n := e.Next()
if time.Since(e.Value.(queued).when) > time.Minute {
q.Remove(e)
e.Value = nil
}
e = n
}
}
}
}()
return
}