-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool_cache.go
More file actions
69 lines (58 loc) · 1.07 KB
/
pool_cache.go
File metadata and controls
69 lines (58 loc) · 1.07 KB
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 pool
import (
"sync"
"time"
"unsafe"
)
const _cacheSize = 10
type poolCache struct {
count int
fulled chan struct{}
tasks []Task
}
func addCache(c chan Task, t Task, cache *poolCache, lock unsafe.Pointer) *poolCache {
var ncache *poolCache
var isfull = cache != nil && cache.count >= _cacheSize
mux := (*sync.Mutex)(lock)
mux.Lock()
defer mux.Unlock()
if cache == nil || isfull {
ncache = &poolCache{
count: 1,
fulled: make(chan struct{}),
tasks: []Task{t},
}
if isfull {
cache.full()
}
cache = ncache
go ncache.await(c, lock)
return ncache
}
cache.count++
cache.tasks = append(cache.tasks, t)
return cache
}
func (pc *poolCache) full() {
close(pc.fulled)
}
func (pc *poolCache) await(c chan Task, lock unsafe.Pointer) {
mux := (*sync.Mutex)(lock)
select {
case <-pc.fulled:
for _, t := range pc.tasks {
c <- t
}
case <-time.After(time.Second):
var ts []Task
if len(pc.tasks) > 0 {
mux.Lock()
ts = append(ts, pc.tasks...)
pc.tasks = pc.tasks[:0]
mux.Unlock()
}
for _, t := range ts {
c <- t
}
}
}