-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.go
54 lines (46 loc) · 976 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
package taskq
import (
"context"
"errors"
"sync"
)
var (
EmptyQueue = errors.New("empty queue")
)
type Queue interface {
Enqueue(context.Context, Task) (int64, error)
// Dequeue Task from queue
// if queue empty return `EmptyQueue` as error
Dequeue(context.Context) (Task, error)
}
type ConcurrentQueue struct {
lock sync.Mutex
lastInc int64
queue []Task
}
func NewConcurrentQueue() *ConcurrentQueue {
return &ConcurrentQueue{}
}
func (q *ConcurrentQueue) Enqueue(_ context.Context, t Task) (int64, error) {
var result int64
q.lock.Lock()
q.queue = append(q.queue, t)
q.lastInc++
result = q.lastInc
q.lock.Unlock()
return result, nil
}
func (q *ConcurrentQueue) Dequeue(_ context.Context) (Task, error) {
q.lock.Lock()
if len(q.queue) == 0 {
q.lock.Unlock()
return nil, EmptyQueue
}
it := q.queue[0]
q.queue = q.queue[1:]
q.lock.Unlock()
return it, nil
}
func (q *ConcurrentQueue) Len(_ context.Context) int {
return len(q.queue)
}