-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphorePool_test.go
126 lines (100 loc) · 2.26 KB
/
semaphorePool_test.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package gopool_test
import (
"bytes"
"fmt"
"sync"
"testing"
"github.com/karrick/gopool"
)
// EXPERIMENT
type SemaphorePool struct {
free []interface{}
getc, putc *sync.Cond // NOTE: both uses same underlying mutex
count, max int
}
func NewSemaphorePool(items []interface{}) (*SemaphorePool, error) {
m := new(sync.Mutex)
s := &SemaphorePool{
free: make([]interface{}, len(items)),
getc: &sync.Cond{L: m},
putc: &sync.Cond{L: m},
count: len(items),
max: len(items),
}
if n := copy(s.free, items); n < len(items) {
return nil, fmt.Errorf("only copied %d out of %d items", n, len(items))
}
return s, nil
}
func (p *SemaphorePool) Close() error {
p.getc.L.Lock()
p.free = nil
// Set count and max such that both Get() and Put() would not block
p.count = 1
p.max = 2
// Unlock all calls to Get() and Put() to prevent go routine leak
p.getc.L.Unlock()
p.getc.Broadcast()
p.putc.Broadcast()
return nil
}
const inplace = false
func (p *SemaphorePool) Get() (item interface{}) {
p.getc.L.Lock()
for p.count == 0 {
p.getc.Wait()
}
if p.free == nil {
panic("Get() after Close()")
}
p.count--
if inplace {
item = p.free[p.count]
} else {
item, p.free = p.free[0], p.free[1:]
}
p.getc.L.Unlock()
p.putc.Signal()
return item
}
func (p *SemaphorePool) Put(item interface{}) {
p.putc.L.Lock()
for p.count == p.max {
p.putc.Wait()
}
if p.free == nil {
panic("Put() after Close()")
}
if inplace {
p.free[p.count] = item
} else {
p.free = append(p.free, item)
}
p.count++
p.putc.L.Unlock()
p.getc.Signal()
}
// TESTING
func newSemaphorePool(tb testing.TB, count int) gopool.Pool {
items := make([]interface{}, count)
for i := 0; i < count; i++ {
items[i] = bytes.NewBuffer(make([]byte, defaultBufSize))
}
pool, err := NewSemaphorePool(items)
if err != nil {
tb.Fatal(err)
}
return pool
}
func TestSemaphorePool(t *testing.T) {
test(t, newSemaphorePool(t, lowCap))
}
func BenchmarkSemaphoreLowConcurrency(b *testing.B) {
bench(b, newSemaphorePool(b, lowCap), lowConcurrency)
}
func BenchmarkSemaphoreMediumConcurrency(b *testing.B) {
bench(b, newSemaphorePool(b, medCap), medConcurrency)
}
func BenchmarkSemaphoreHighConcurrency(b *testing.B) {
bench(b, newSemaphorePool(b, largeCap), highConcurrency)
}