forked from panjf2000/ants
-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker_map.go
77 lines (65 loc) Β· 1.34 KB
/
worker_map.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
package ants
import (
"errors"
"time"
)
type workerMap struct {
items map[int]worker
expiry []worker
}
func newWorkerMap(size int) *workerMap {
return &workerMap{
items: map[int]worker{},
}
}
func (wq *workerMap) len() int {
return len(wq.items)
}
func (wq *workerMap) isEmpty() bool {
return len(wq.items) == 0
}
func (wq *workerMap) insert(w worker) error {
idw, ok := w.(*goWorkerWithID)
if !ok {
return errors.New("workerMap only accept goWorkerWithID")
}
wq.items[idw.id] = w
return nil
}
func (wq *workerMap) detach() worker {
panic("workerMap detach unreachable,instead of get(id)")
}
func (wq *workerMap) get(id int, now time.Time) worker {
w, ok := wq.items[id]
if !ok {
return w
}
w.(*goWorkerWithID).lastUsed = now
return wq.items[id]
}
func (wq *workerMap) detachWithID(id int) worker {
w := wq.items[id]
delete(wq.items, id)
return w
}
func (wq *workerMap) refresh(duration time.Duration) []worker {
n := wq.len()
if n == 0 {
return nil
}
expiryTime := time.Now().Add(-duration)
wq.expiry = wq.expiry[:0]
for _, w := range wq.items {
if expiryTime.Before(w.lastUsedTime()) {
wq.expiry = append(wq.expiry, w)
delete(wq.items, w.(*goWorkerWithID).id)
}
}
return wq.expiry
}
func (wq *workerMap) reset() {
for _, w := range wq.items {
w.finish()
delete(wq.items, w.(*goWorkerWithID).id)
}
}