2020-02-21 07:44:17 +08:00
|
|
|
package util
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
|
|
|
type UnboundedQueue struct {
|
|
|
|
outbound []string
|
|
|
|
outboundLock sync.RWMutex
|
|
|
|
inbound []string
|
|
|
|
inboundLock sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewUnboundedQueue() *UnboundedQueue {
|
|
|
|
q := &UnboundedQueue{}
|
|
|
|
return q
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q *UnboundedQueue) EnQueue(items ...string) {
|
|
|
|
q.inboundLock.Lock()
|
|
|
|
defer q.inboundLock.Unlock()
|
|
|
|
|
2020-03-21 14:39:32 +08:00
|
|
|
q.inbound = append(q.inbound, items...)
|
2020-02-21 07:44:17 +08:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q *UnboundedQueue) Consume(fn func([]string)) {
|
|
|
|
q.outboundLock.Lock()
|
|
|
|
defer q.outboundLock.Unlock()
|
|
|
|
|
|
|
|
if len(q.outbound) == 0 {
|
|
|
|
q.inboundLock.Lock()
|
2022-09-15 01:12:45 +08:00
|
|
|
inboundLen := len(q.inbound)
|
|
|
|
if inboundLen > 0 {
|
2020-02-21 07:44:17 +08:00
|
|
|
t := q.outbound
|
|
|
|
q.outbound = q.inbound
|
|
|
|
q.inbound = t
|
|
|
|
}
|
|
|
|
q.inboundLock.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(q.outbound) > 0 {
|
|
|
|
fn(q.outbound)
|
|
|
|
q.outbound = q.outbound[:0]
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|