-
Notifications
You must be signed in to change notification settings - Fork 292
/
Copy pathqueue.go
67 lines (53 loc) · 975 Bytes
/
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
package queue
import (
"errors"
"sync"
)
type T interface{}
var (
errFull = errors.New("full")
errNoTask = errors.New("no task")
)
type CircularBuffer struct {
sync.Mutex
taskQueue []T
capacity int
head int
tail int
full bool
}
func (s *CircularBuffer) IsEmpty() bool {
return s.head == s.tail && !s.full
}
func (s *CircularBuffer) IsFull() bool {
return s.full
}
func (s *CircularBuffer) Enqueue(task T) error {
if s.IsFull() {
return errFull
}
s.Lock()
s.taskQueue[s.tail] = task
s.tail = (s.tail + 1) % s.capacity
s.full = s.head == s.tail
s.Unlock()
return nil
}
func (s *CircularBuffer) Dequeue() (T, error) {
if s.IsEmpty() {
return nil, errNoTask
}
s.Lock()
data := s.taskQueue[s.head]
s.full = false
s.head = (s.head + 1) % s.capacity
s.Unlock()
return data, nil
}
func NewCircularBuffer(size int) *CircularBuffer {
w := &CircularBuffer{
taskQueue: make([]T, size),
capacity: size,
}
return w
}