forked from cloudfoundry/auctioneer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker_pool.go
101 lines (82 loc) · 2.1 KB
/
worker_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
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
package workerpool
import (
"sync"
"time"
)
type WorkerPool struct {
workQueue chan func()
workerCloseChannel chan bool
workerCount float64
workerMutex sync.WaitGroup
metricsLock sync.Mutex
timeSpentWorking time.Duration
usageSampleStartTime time.Time
}
func NewWorkerPool(poolSize int) (pool *WorkerPool) {
pool = &WorkerPool{
workQueue: make(chan func(), 0),
workerCloseChannel: make(chan bool),
usageSampleStartTime: time.Now(),
workerCount: float64(poolSize),
}
for i := 0; i < poolSize; i++ {
pool.workerMutex.Add(1)
go pool.startWorker(pool.workQueue, pool.workerCloseChannel)
}
return
}
func (pool *WorkerPool) ScheduleWork(work func()) {
select {
case <-pool.workerCloseChannel:
return
default:
go func() {
pool.workQueue <- work
}()
}
}
func (pool *WorkerPool) StopWorkers() {
select {
case <-pool.workerCloseChannel:
return
default:
close(pool.workerCloseChannel)
pool.workerMutex.Wait()
}
}
func (pool *WorkerPool) startWorker(workChannel chan func(), closeChannel chan bool) {
defer pool.workerMutex.Done()
for {
select {
case f := <-workChannel:
tWork := time.Now()
f()
dtWork := time.Since(tWork)
pool.addTimeSpentWorking(dtWork)
case <-closeChannel:
return
}
}
}
func (pool *WorkerPool) StartTrackingUsage() {
pool.resetUsageMetrics()
}
func (pool *WorkerPool) MeasureUsage() (usage float64, timeSinceStartTime time.Duration) {
timeSpentWorking, timeSinceStartTime := pool.resetUsageMetrics()
usage = timeSpentWorking / (timeSinceStartTime.Seconds() * pool.workerCount)
return
}
func (pool *WorkerPool) addTimeSpentWorking(moreTime time.Duration) {
pool.metricsLock.Lock()
defer pool.metricsLock.Unlock()
pool.timeSpentWorking += moreTime
}
func (pool *WorkerPool) resetUsageMetrics() (timeSpentWorking float64, timeSinceStartTime time.Duration) {
pool.metricsLock.Lock()
defer pool.metricsLock.Unlock()
timeSinceStartTime = time.Since(pool.usageSampleStartTime)
timeSpentWorking = pool.timeSpentWorking.Seconds()
pool.usageSampleStartTime = time.Now()
pool.timeSpentWorking = 0
return
}