-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncqueue.go
92 lines (77 loc) · 1.66 KB
/
syncqueue.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package syncq
// Copy from: https://github.com/xiaonanln/go-xnsyncutil/blob/master/xnsyncutil/sync_queue.go
import (
"github.com/eapache/queue"
"sync"
)
// SyncQueue Synchronous FIFO queue
type SyncQueue struct {
lock sync.Mutex
popable *sync.Cond
buffer *queue.Queue
closed bool
}
// NewSyncQueue Create a new SyncQueue
func NewSyncQueue() *SyncQueue {
ch := &SyncQueue{
buffer: queue.New(),
}
ch.popable = sync.NewCond(&ch.lock)
return ch
}
// Pop an item from SyncQueue, will block if SyncQueue is empty
func (q *SyncQueue) Pop() (v interface{}) {
c := q.popable
buffer := q.buffer
q.lock.Lock()
for buffer.Length() == 0 && !q.closed {
c.Wait()
}
if buffer.Length() > 0 {
v = buffer.Peek()
buffer.Remove()
}
q.lock.Unlock()
return
}
// TryPop Try to pop an item from SyncQueue, will return immediately with bool=false if SyncQueue is empty
func (q *SyncQueue) TryPop() (v interface{}, ok bool) {
buffer := q.buffer
q.lock.Lock()
if buffer.Length() > 0 {
v = buffer.Peek()
buffer.Remove()
ok = true
} else if q.closed {
ok = true
}
q.lock.Unlock()
return
}
// Push an item to SyncQueue. Always returns immediately without blocking
func (q *SyncQueue) Push(v interface{}) {
q.lock.Lock()
if !q.closed {
q.buffer.Add(v)
q.popable.Signal()
}
q.lock.Unlock()
}
// Len Get the length of SyncQueue
func (q *SyncQueue) Len() (l int) {
q.lock.Lock()
l = q.buffer.Length()
q.lock.Unlock()
return
}
// Close SyncQueue
//
// After close, Pop will return nil without block, and TryPop will return v=nil, ok=True
func (q *SyncQueue) Close() {
q.lock.Lock()
if !q.closed {
q.closed = true
q.popable.Signal()
}
q.lock.Unlock()
}