ants/worker_loop_queue.go

120 lines
1.7 KiB
Go
Raw Normal View History

package ants
import "time"
type loopQueue struct {
2019-10-20 13:22:13 +03:00
items []*goWorker
expiry []*goWorker
head int
tail int
size int
isFull bool
}
func newWorkerLoopQueue(size int) *loopQueue {
2019-10-20 13:22:13 +03:00
return &loopQueue{
items: make([]*goWorker, size),
size: size,
}
}
func (wq *loopQueue) len() int {
2019-10-20 13:22:13 +03:00
if wq.size == 0 {
return 0
}
2019-10-20 13:22:13 +03:00
if wq.head == wq.tail {
if wq.isFull {
return wq.size
}
return 0
}
if wq.tail > wq.head {
return wq.tail - wq.head
}
return wq.size - wq.head + wq.tail
}
func (wq *loopQueue) isEmpty() bool {
2019-10-20 13:22:13 +03:00
return wq.head == wq.tail && !wq.isFull
}
func (wq *loopQueue) insert(worker *goWorker) error {
2019-10-20 13:22:13 +03:00
if wq.size == 0 {
return errQueueIsReleased
}
2019-10-20 13:22:13 +03:00
if wq.isFull {
return errQueueIsFull
}
wq.items[wq.tail] = worker
2019-10-20 13:22:13 +03:00
wq.tail++
if wq.tail == wq.size {
wq.tail = 0
}
if wq.tail == wq.head {
wq.isFull = true
}
return nil
}
func (wq *loopQueue) detach() *goWorker {
2019-10-20 13:22:13 +03:00
if wq.isEmpty() {
return nil
}
w := wq.items[wq.head]
2020-08-29 13:51:56 +03:00
wq.items[wq.head] = nil
2019-10-20 13:22:13 +03:00
wq.head++
if wq.head == wq.size {
wq.head = 0
}
wq.isFull = false
return w
}
2019-10-20 13:22:13 +03:00
func (wq *loopQueue) retrieveExpiry(duration time.Duration) []*goWorker {
if wq.isEmpty() {
return nil
}
wq.expiry = wq.expiry[:0]
expiryTime := time.Now().Add(-duration)
2019-10-20 13:22:13 +03:00
for !wq.isEmpty() {
if expiryTime.Before(wq.items[wq.head].recycleTime) {
break
}
wq.expiry = append(wq.expiry, wq.items[wq.head])
2020-08-29 13:51:56 +03:00
wq.items[wq.head] = nil
2019-10-20 13:22:13 +03:00
wq.head++
if wq.head == wq.size {
wq.head = 0
}
wq.isFull = false
}
2019-10-20 13:22:13 +03:00
return wq.expiry
}
2019-10-20 13:22:13 +03:00
func (wq *loopQueue) reset() {
if wq.isEmpty() {
return
}
2019-10-20 13:22:13 +03:00
Releasing:
if w := wq.detach(); w != nil {
w.task <- nil
goto Releasing
}
wq.items = wq.items[:0]
2019-10-20 13:22:13 +03:00
wq.size = 0
wq.head = 0
wq.tail = 0
}