-
Notifications
You must be signed in to change notification settings - Fork 1
/
lifo_memory_queue.go
101 lines (93 loc) · 2.09 KB
/
lifo_memory_queue.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
93
94
95
96
97
98
99
100
101
package queue
import (
"context"
"sync"
)
func NewLifoMemoryQueue(sizes ...int) Queue {
ctx, cancel := context.WithCancel(context.Background())
size := 1024
if len(sizes) > 0 {
size = sizes[0]
}
return &LifoMemoryQueue{
queue: make([][]byte, size, size),
ctx: ctx,
cancel: cancel,
putNotify: make(chan struct{}, size),
getNotify: make(chan struct{}, size),
}
}
var _ Queue = (*LifoMemoryQueue)(nil)
type LifoMemoryQueue struct {
queue [][]byte
ctx context.Context
cancel context.CancelFunc
lock sync.Mutex
index int
getNotify chan struct{}
putNotify chan struct{}
}
func (q *LifoMemoryQueue) Get(ctx context.Context) ([]byte, error) {
select {
case <-q.ctx.Done():
return nil, ErrQueueClosed
default:
}
if ctx != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-q.ctx.Done():
return nil, ErrQueueClosed
case <-q.getNotify: // 阻塞,则表示当前队列无数据
}
}
q.lock.Lock()
defer q.lock.Unlock()
if q.index <= 0 {
return nil, ErrQueueEmpty
}
q.index--
data := q.queue[q.index]
q.queue[q.index] = nil
<-q.putNotify
if ctx == nil {
<-q.getNotify
}
return data, nil
}
func (q *LifoMemoryQueue) Put(ctx context.Context, data []byte) error {
select {
case <-q.ctx.Done():
return ErrQueueClosed
default:
}
if ctx != nil {
select {
case <-ctx.Done():
return ctx.Err()
case <-q.ctx.Done():
return ErrQueueClosed
case q.putNotify <- struct{}{}:
}
}
q.lock.Lock()
defer q.lock.Unlock()
if q.index >= len(q.queue) {
return ErrQueueFull
}
q.queue[q.index] = data
q.index++
q.getNotify <- struct{}{}
if ctx == nil {
q.putNotify <- struct{}{}
}
return nil
}
func (q *LifoMemoryQueue) Close() error {
q.cancel()
return nil
}
func (q *LifoMemoryQueue) Len() int {
return q.index
}