2019-10-09 19:59:19 +03:00
|
|
|
package ants
|
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
|
|
|
type loopQueue struct {
|
|
|
|
items []*goWorker
|
|
|
|
expiry []*goWorker
|
|
|
|
head int
|
|
|
|
tail int
|
|
|
|
remainder int
|
|
|
|
}
|
|
|
|
|
2019-10-09 22:02:04 +03:00
|
|
|
func newWorkerLoopQueue(size int) *loopQueue {
|
2019-10-09 19:59:19 +03:00
|
|
|
if size <= 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
wq := loopQueue{
|
|
|
|
items: make([]*goWorker, size+1),
|
|
|
|
head: 0,
|
|
|
|
tail: 0,
|
|
|
|
remainder: size + 1,
|
|
|
|
}
|
|
|
|
|
|
|
|
return &wq
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wq *loopQueue) len() int {
|
|
|
|
if wq.remainder == 0 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return (wq.tail - wq.head + wq.remainder) % wq.remainder
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wq *loopQueue) isEmpty() bool {
|
|
|
|
return wq.tail == wq.head
|
|
|
|
}
|
|
|
|
|
2019-10-09 22:02:04 +03:00
|
|
|
func (wq *loopQueue) insert(worker *goWorker) error {
|
2019-10-09 19:59:19 +03:00
|
|
|
if wq.remainder == 0 {
|
|
|
|
return ErrQueueLengthIsZero
|
|
|
|
}
|
2019-10-09 22:02:04 +03:00
|
|
|
next := (wq.tail + 1) % wq.remainder
|
|
|
|
if next == wq.head {
|
2019-10-09 19:59:19 +03:00
|
|
|
return ErrQueueIsFull
|
|
|
|
}
|
|
|
|
|
|
|
|
wq.items[wq.tail] = worker
|
2019-10-09 22:02:04 +03:00
|
|
|
wq.tail = next
|
2019-10-09 19:59:19 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-10-09 22:02:04 +03:00
|
|
|
func (wq *loopQueue) detach() *goWorker {
|
2019-10-09 19:59:19 +03:00
|
|
|
if wq.len() == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
w := wq.items[wq.head]
|
|
|
|
wq.head = (wq.head + 1) % wq.remainder
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2019-10-09 22:02:04 +03:00
|
|
|
func (wq *loopQueue) findOutExpiry(duration time.Duration) []*goWorker {
|
2019-10-09 19:59:19 +03:00
|
|
|
if wq.len() == 0 {
|
2019-10-09 22:02:04 +03:00
|
|
|
return nil
|
2019-10-09 19:59:19 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
wq.expiry = wq.expiry[:0]
|
|
|
|
expiryTime := time.Now().Add(-duration)
|
|
|
|
|
|
|
|
for wq.head != wq.tail {
|
2019-10-09 22:02:04 +03:00
|
|
|
if expiryTime.Before(wq.items[wq.head].recycleTime) {
|
|
|
|
break
|
2019-10-09 19:59:19 +03:00
|
|
|
}
|
2019-10-09 22:02:04 +03:00
|
|
|
wq.expiry = append(wq.expiry, wq.items[wq.head])
|
|
|
|
wq.head = (wq.head + 1) % wq.remainder
|
2019-10-09 19:59:19 +03:00
|
|
|
}
|
2019-10-09 22:02:04 +03:00
|
|
|
return wq.expiry
|
2019-10-09 19:59:19 +03:00
|
|
|
}
|
|
|
|
|
2019-10-09 22:02:04 +03:00
|
|
|
func (wq *loopQueue) release() {
|
2019-10-09 19:59:19 +03:00
|
|
|
if wq.len() == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for wq.head != wq.tail {
|
|
|
|
wq.items[wq.head].task <- nil
|
|
|
|
wq.head = (wq.head + 1) % wq.remainder
|
|
|
|
}
|
|
|
|
wq.items = wq.items[:0]
|
|
|
|
wq.remainder = 0
|
|
|
|
wq.head = 0
|
|
|
|
wq.tail = 0
|
|
|
|
}
|