forked from Tnze/go-mc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
83 lines (71 loc) · 1.25 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
package queue
import (
"container/list"
"sync"
)
type Queue[T any] interface {
Push(v T) (ok bool)
Pull() (v T, ok bool)
Close()
}
func NewLinkedQueue[T any]() (q Queue[T]) {
return &LinkedListQueue[T]{
queue: list.New(),
cond: sync.Cond{L: new(sync.Mutex)},
}
}
type LinkedListQueue[T any] struct {
queue *list.List
closed bool
cond sync.Cond
}
func (p *LinkedListQueue[T]) Push(v T) bool {
p.cond.L.Lock()
if p.closed {
panic("push on closed queue")
}
p.queue.PushBack(v)
p.cond.Signal()
p.cond.L.Unlock()
return true
}
func (p *LinkedListQueue[T]) Pull() (v T, ok bool) {
p.cond.L.Lock()
for {
if elem := p.queue.Front(); elem != nil {
v = p.queue.Remove(elem).(T)
ok = true
break
} else if p.closed {
break
}
p.cond.Wait()
}
p.cond.L.Unlock()
return
}
func (p *LinkedListQueue[T]) Close() {
p.cond.L.Lock()
p.closed = true
p.cond.Broadcast()
p.cond.L.Unlock()
}
func NewChannelQueue[T any](n int) (q Queue[T]) {
return make(ChannelQueue[T], n)
}
type ChannelQueue[T any] chan T
func (c ChannelQueue[T]) Push(v T) bool {
select {
case c <- v:
return true
default:
return false
}
}
func (c ChannelQueue[T]) Pull() (v T, ok bool) {
v, ok = <-c
return
}
func (c ChannelQueue[T]) Close() {
close(c)
}