-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunnableQueue.go
More file actions
96 lines (82 loc) · 1.77 KB
/
Copy pathrunnableQueue.go
File metadata and controls
96 lines (82 loc) · 1.77 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
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
package jobsd
import (
"container/heap"
"sync"
)
type runnableQueue []*Runnable
func (pq *runnableQueue) Len() int { return len(*pq) }
func (pq *runnableQueue) Less(i, j int) bool {
return (*pq)[i].runAt().Before((*pq)[j].runAt())
}
func (pq *runnableQueue) Swap(i, j int) {
(*pq)[i], (*pq)[j] = (*pq)[j], (*pq)[i]
}
func (pq *runnableQueue) Push(x interface{}) {
item := x.(*Runnable)
*pq = append(*pq, item)
}
func (pq *runnableQueue) Pop() interface{} {
n := len(runnableQueue(*pq))
x := runnableQueue(*pq)[n-1]
*pq = runnableQueue(*pq)[0 : n-1]
return x
}
func (pq *runnableQueue) Peek() *Runnable {
if pq.Len() <= 0 {
return &Runnable{}
}
return (*pq)[0]
}
// RunnableQueue is a priority queue of jobs to run
type RunnableQueue struct {
mx sync.Mutex
queue *runnableQueue
dup map[string]struct{}
}
// Push .
func (q *RunnableQueue) Push(j *Runnable) bool {
q.mx.Lock()
defer q.mx.Unlock()
if !j.jobRun.NameActive.Valid {
return false
}
if _, ok := q.dup[j.jobRun.NameActive.String]; ok {
return false // this de-duplicates
}
q.dup[j.jobRun.NameActive.String] = struct{}{}
heap.Push(q.queue, j)
return true
}
// Pop .
func (q *RunnableQueue) Pop() *Runnable {
q.mx.Lock()
defer q.mx.Unlock()
if q.queue.Len() <= 0 {
return &Runnable{}
}
rtn := heap.Pop(q.queue).(*Runnable)
delete(q.dup, rtn.jobRun.NameActive.String)
return rtn
}
// Peek .
func (q *RunnableQueue) Peek() *Runnable {
q.mx.Lock()
defer q.mx.Unlock()
if q.queue.Len() <= 0 {
return &Runnable{}
}
return q.queue.Peek()
}
// Len .
func (q *RunnableQueue) Len() int {
q.mx.Lock()
defer q.mx.Unlock()
return q.queue.Len()
}
// NewRunnableQueue .
func NewRunnableQueue() *RunnableQueue {
return &RunnableQueue{
queue: &runnableQueue{},
dup: map[string]struct{}{},
}
}