-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorvenor.go
88 lines (79 loc) · 1.72 KB
/
gorvenor.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
package jobqueue
import (
"sync"
"time"
)
//OndemandGovernor ondemand governor
func NewLocalOndemandGovernor(max, min, maxworker int, jd map[string]JobDescription) Governor {
curr := max
jc := make(map[string]*int)
for k := range jd {
jc[k] = new(int)
}
return &LocalOndemandGovernor{
WorkerCounter: new(int),
MaxWorker: maxworker,
MaxSleep: max,
MinSleep: min,
CurSleep: &curr,
Locker: new(sync.Mutex),
JobCounter: jc,
JobDescription: jd,
}
}
type LocalOndemandGovernor struct {
MaxSleep int
MinSleep int
CurSleep *int
WorkerCounter *int
Locker *sync.Mutex
JobCounter map[string]*int
MaxWorker int
JobDescription map[string]JobDescription
}
func (g LocalOndemandGovernor) AddJob(title string) {
g.Locker.Lock()
defer g.Locker.Unlock()
*g.CurSleep = g.MinSleep
*g.JobCounter[title] += 1
*g.WorkerCounter += 1
}
func (g LocalOndemandGovernor) DelJob(title string) {
g.Locker.Lock()
defer g.Locker.Unlock()
*g.JobCounter[title] -= 1
*g.WorkerCounter -= 1
}
func (g LocalOndemandGovernor) NoJob() {
t := *g.CurSleep
t *= 2
if t > g.MaxSleep {
t = g.MaxSleep
}
*g.CurSleep = t
}
func (g LocalOndemandGovernor) Spawn() (bool, []string) {
bl := make([]string, 0)
for k, v := range g.JobDescription {
if v.Secure {
g.Locker.Lock()
if *g.JobCounter[k] >= v.Concurrent {
bl = append(bl, k)
}
g.Locker.Unlock()
} else {
if *g.JobCounter[k] >= v.Concurrent {
bl = append(bl, k)
}
}
}
time.Sleep(time.Duration(*g.CurSleep) * time.Millisecond)
if *g.WorkerCounter < g.MaxWorker {
return true, bl
}
g.NoJob()
return false, bl
}
func (g LocalOndemandGovernor) GetCounter() int {
return *g.WorkerCounter
}