blob: 81ab69185a942a41f90b6fc41bab8136717346cc (
plain)
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
|
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()
q.inbound = append(q.inbound, items...)
}
func (q *UnboundedQueue) Consume(fn func([]string)) {
q.outboundLock.Lock()
defer q.outboundLock.Unlock()
if len(q.outbound) == 0 {
q.inboundLock.Lock()
inboundLen := len(q.inbound)
if inboundLen > 0 {
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]
}
}
|