priopool/queue.go

53 lines
1.1 KiB
Go
Raw Normal View History

2021-10-23 15:16:40 +00:00
package priopool
2021-10-20 14:02:55 +00:00
2021-10-23 15:16:40 +00:00
// Priority pool based on implementation example from heap package.
// Priority queue itself is not thread safe.
// See https://cs.opensource.google/go/go/+/refs/tags/go1.17.2:src/container/heap/example_pq_test.go
2021-10-20 14:02:55 +00:00
import (
"container/heap"
)
2021-10-23 15:16:40 +00:00
type priorityQueueTask struct {
value func()
priority int
index int // the index is needed by update and is maintained by the heap.Interface methods
2021-10-20 14:02:55 +00:00
}
2021-10-23 15:16:40 +00:00
type priorityQueue []*priorityQueueTask
2021-10-20 14:02:55 +00:00
2021-10-23 15:16:40 +00:00
func (pq priorityQueue) Len() int { return len(pq) }
2021-10-20 14:02:55 +00:00
2021-10-23 15:16:40 +00:00
func (pq priorityQueue) Less(i, j int) bool {
2021-10-20 14:02:55 +00:00
return pq[i].priority > pq[j].priority
}
2021-10-23 15:16:40 +00:00
func (pq priorityQueue) Swap(i, j int) {
2021-10-20 14:02:55 +00:00
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
2021-10-23 15:16:40 +00:00
func (pq *priorityQueue) Push(x interface{}) {
2021-10-20 14:02:55 +00:00
n := len(*pq)
2021-10-23 15:16:40 +00:00
item := x.(*priorityQueueTask)
2021-10-20 14:02:55 +00:00
item.index = n
*pq = append(*pq, item)
}
2021-10-23 15:16:40 +00:00
func (pq *priorityQueue) Pop() interface{} {
2021-10-20 14:02:55 +00:00
old := *pq
n := len(old)
item := old[n-1]
2021-10-23 15:16:40 +00:00
old[n-1] = nil
item.index = -1
2021-10-20 14:02:55 +00:00
*pq = old[0 : n-1]
return item
}
2021-10-23 15:16:40 +00:00
func (pq *priorityQueue) update(item *priorityQueueTask, value func(), priority int) {
2021-10-20 14:02:55 +00:00
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}