-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathconc_queue.go
More file actions
77 lines (67 loc) · 1.6 KB
/
Copy pathconc_queue.go
File metadata and controls
77 lines (67 loc) · 1.6 KB
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
package fn
// ConcurrentQueue is an unbounded concurrent queue. Items sent to ChanIn are
// buffered internally (using a List for overflow) and delivered to ChanOut in
// FIFO order
type ConcurrentQueue[T any] struct {
chanIn chan T
chanOut chan T
quit chan struct{}
buf *List[T]
}
// NewConcurrentQueue creates a new ConcurrentQueue
func NewConcurrentQueue[T any]() *ConcurrentQueue[T] {
return &ConcurrentQueue[T]{
chanIn: make(chan T),
chanOut: make(chan T),
quit: make(chan struct{}),
buf: NewList[T](),
}
}
// ChanIn returns the channel to send items into
func (q *ConcurrentQueue[T]) ChanIn() chan<- T {
return q.chanIn
}
// ChanOut returns the channel to receive items from
func (q *ConcurrentQueue[T]) ChanOut() <-chan T {
return q.chanOut
}
// Start begins processing. Must be called before sending/receiving
func (q *ConcurrentQueue[T]) Start() {
go q.run()
}
// Stop shuts down the queue
func (q *ConcurrentQueue[T]) Stop() {
close(q.quit)
}
// run is the internal goroutine that shuttles items from chanIn through the
// buffer to chanOut
func (q *ConcurrentQueue[T]) run() {
for {
if q.buf.Len() == 0 {
// Buffer is empty; wait for input or quit
select {
case item, ok := <-q.chanIn:
if !ok {
return
}
q.buf.PushBack(item)
case <-q.quit:
return
}
} else {
// Buffer has items; try to send or receive
front := q.buf.Front().Value
select {
case item, ok := <-q.chanIn:
if !ok {
return
}
q.buf.PushBack(item)
case q.chanOut <- front:
q.buf.Remove(q.buf.Front())
case <-q.quit:
return
}
}
}
}