-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbufpool.go
65 lines (55 loc) · 1.48 KB
/
bufpool.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
// bufpool.go -- Buffer pool (blocking) abstraction
//
// (c) 2015, 2016 -- Sudhi Herle <sudhi@herle.net>
//
// Licensing Terms: GPLv2
//
// If you need a commercial license for this work, please contact
// the author.
//
// This software does not come with any express or implied
// warranty; it is provided "as is". No claim is made to its
// suitability for any purpose.
package utils
// A fixed-size buffer-pool backed by a channel and hence, callers
// are blocked if there are no more buffers available.
// Callers are expected to free the buffer back to its
// originating pool.
type Bufpool struct {
Size int
q chan interface{}
}
// Default pool size
const Poolsize = 64
// NewBufpool creates a new Bufpool. The caller supplies a
// constructor for creating new buffers and filling the
// queue with initial elements.
func NewBufpool(sz int, ctor func() interface{}) *Bufpool {
if sz <= 0 {
sz = Poolsize
}
b := &Bufpool{Size: sz}
b.q = make(chan interface{}, sz)
for i := 0; i < sz; i++ {
b.q <- ctor()
}
return b
}
// Put an item into the bufpool. This should not ever block; it
// indicates pool integrity failure (duplicates or erroneous Puts).
func (b *Bufpool) Put(o interface{}) {
select {
case b.q <- o:
break
default:
panic("Bufpool put blocked. Queue corrupt?")
}
}
// Get the next available item from the pool; block the caller if
// none are available.
func (b *Bufpool) Get() interface{} {
o := <-b.q
return o
}
// EOF
// vim: ft=go:sw=8:ts=8:noexpandtab:tw=98: