-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
89 lines (68 loc) · 1.38 KB
/
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
package algo
import (
"fmt"
"io"
"sync"
)
// Queue uses an array as the underlying data structure.
type Queue[T any] struct {
mu sync.RWMutex
data []T
}
func NewQueue[T any]() *Queue[T] {
return &Queue[T]{
mu: sync.RWMutex{},
data: []T{},
}
}
func (q *Queue[T]) enqueue(v T) {
q.mu.Lock()
defer q.mu.Unlock()
q.data = append(q.data, v)
}
func (q *Queue[T]) dequeue() T {
q.mu.Lock()
defer q.mu.Unlock()
if q.isEmpty() {
return q.nilType()
}
v := q.data[0]
// q.data[0] = nil
q.data = q.data[1:]
return v
}
func (q *Queue[T]) peak() T {
q.mu.RLock()
defer q.mu.RUnlock()
if q.isEmpty() {
return q.nilType()
}
return q.data[0]
}
func (q *Queue[T]) isEmpty() bool {
// no locking, as this is internal and should be done by caller.
return len(q.data) == 0
}
func (q *Queue[T]) nilType() T {
var t T
return t
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Usecase: print manager
type PrintManager struct {
queue *Queue[string]
}
func newPrintMgr() *PrintManager {
return &PrintManager{queue: NewQueue[string]()}
}
func (p *PrintManager) queuePrintJob(document string) {
p.queue.enqueue(document)
}
func (p *PrintManager) run(out io.Writer) {
for len(p.queue.data) > 0 {
printer(out, p.queue.dequeue())
}
}
func printer(out io.Writer, doc string) {
fmt.Fprintln(out, doc)
}