-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent_pqueue.go
75 lines (60 loc) · 1.36 KB
/
concurrent_pqueue.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
package carrot
import (
"container/heap"
"sync"
)
type ConcurrentPriorityQueue struct {
pq *priorityQueue
mu *sync.Mutex
}
func newConcurrentPriorityQueue(capacity int) *ConcurrentPriorityQueue {
pq := newPriorityQueue(capacity)
heap.Init(pq)
cpq := ConcurrentPriorityQueue{
pq: pq,
mu: new(sync.Mutex),
}
return &cpq
}
// enqueue pushes the element x onto the heap.
func (cpq *ConcurrentPriorityQueue) enqueue(ce *cacheEntry) {
cpq.mu.Lock()
heap.Push(cpq.pq, ce)
cpq.mu.Unlock()
}
// dequeue remove and return first element.
func (cpq *ConcurrentPriorityQueue) dequeue(limit int64) (*cacheEntry, bool) {
cpq.mu.Lock()
defer cpq.mu.Unlock()
if cpq.pq.isEmpty() {
return nil, false
}
ce := (*cpq.pq)[0]
if ce.priority > limit {
return nil, false
}
heap.Remove(cpq.pq, 0)
return ce, true
}
// update modifies the element in the queue.
func (cpq *ConcurrentPriorityQueue) update(ce *cacheEntry) {
cpq.mu.Lock()
heap.Fix(cpq.pq, ce.index)
cpq.mu.Unlock()
}
// remove removes the element at index i from the heap.
func (cpq *ConcurrentPriorityQueue) remove(ce *cacheEntry) {
cpq.mu.Lock()
defer cpq.mu.Unlock()
l := cpq.pq.Len()
if l == 0 || l <= ce.index || ce.index < 0 {
return
}
heap.Remove(cpq.pq, ce.index)
}
// eraseMap removes all elements
func (cpq *ConcurrentPriorityQueue) erase() {
cpq.mu.Lock()
cpq.pq.clear()
cpq.mu.Unlock()
}