forked from smallnest/rpcx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
69 lines (57 loc) ยท 1.07 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
package server
import (
"reflect"
"sync"
)
var UsePool bool
// Reset defines Reset method for pooled object.
type Reset interface {
Reset()
}
var argsReplyPools = &typePools{
pools: make(map[reflect.Type]*sync.Pool),
New: func(t reflect.Type) interface{} {
var argv reflect.Value
if t.Kind() == reflect.Ptr { // reply must be ptr
argv = reflect.New(t.Elem())
} else {
argv = reflect.New(t)
}
return argv.Interface()
},
}
type typePools struct {
mu sync.RWMutex
pools map[reflect.Type]*sync.Pool
New func(t reflect.Type) interface{}
}
func (p *typePools) Init(t reflect.Type) {
tp := &sync.Pool{}
tp.New = func() interface{} {
return p.New(t)
}
p.mu.Lock()
defer p.mu.Unlock()
p.pools[t] = tp
}
func (p *typePools) Put(t reflect.Type, x interface{}) {
if !UsePool {
return
}
if o, ok := x.(Reset); ok {
o.Reset()
}
p.mu.RLock()
pool := p.pools[t]
p.mu.RUnlock()
pool.Put(x)
}
func (p *typePools) Get(t reflect.Type) interface{} {
if !UsePool {
return p.New(t)
}
p.mu.RLock()
pool := p.pools[t]
p.mu.RUnlock()
return pool.Get()
}