-
Notifications
You must be signed in to change notification settings - Fork 179
/
concurrentqueue.go
63 lines (47 loc) · 984 Bytes
/
concurrentqueue.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
package concurrentqueue
import (
"sync"
"github.com/ef-ds/deque"
)
// ConcurrentQueue implements a thread safe interface for unbounded FIFO queue.
type ConcurrentQueue struct {
q deque.Deque
m sync.Mutex
}
func (s *ConcurrentQueue) Len() int {
s.m.Lock()
defer s.m.Unlock()
return s.q.Len()
}
func (s *ConcurrentQueue) Push(v interface{}) {
s.m.Lock()
defer s.m.Unlock()
s.q.PushBack(v)
}
func (s *ConcurrentQueue) Pop() (interface{}, bool) {
s.m.Lock()
defer s.m.Unlock()
return s.q.PopFront()
}
func (s *ConcurrentQueue) PopBatch(batchSize int) ([]interface{}, bool) {
s.m.Lock()
defer s.m.Unlock()
count := s.q.Len()
if count == 0 {
return nil, false
}
if count > batchSize {
count = batchSize
}
result := make([]interface{}, count)
for i := 0; i < count; i++ {
v, _ := s.q.PopFront()
result[i] = v
}
return result, true
}
func (s *ConcurrentQueue) Front() (interface{}, bool) {
s.m.Lock()
defer s.m.Unlock()
return s.q.Front()
}