-
Notifications
You must be signed in to change notification settings - Fork 1
/
linked_queue.go
76 lines (65 loc) · 1.15 KB
/
linked_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
package collections
import (
"math"
"sync"
)
type linkedNode[T any] struct {
val T
next *linkedNode[T]
}
type LinkedQueue[T any] struct {
head *linkedNode[T]
tail *linkedNode[T]
lock *sync.Mutex
putCond *sync.Cond
takeCond *sync.Cond
capacity int
count int
}
func NewLinkedQueue[T any](capacity int) *LinkedQueue[T] {
if capacity <= 0 {
capacity = math.MaxInt
}
lock := &sync.Mutex{}
return &LinkedQueue[T]{
lock: lock,
putCond: sync.NewCond(lock),
takeCond: sync.NewCond(lock),
capacity: capacity,
}
}
func (l *LinkedQueue[T]) Enqueue(value T) (success bool) {
l.lock.Lock()
defer l.lock.Unlock()
for l.count == l.capacity {
l.putCond.Wait()
}
n := &linkedNode[T]{value, nil}
if l.tail != nil {
l.tail.next = n
}
l.tail = n
if l.count == 0 {
l.head = l.tail
}
l.count++
l.takeCond.Signal()
return true
}
func (l *LinkedQueue[T]) Dequeue() (value T, success bool) {
l.lock.Lock()
defer l.lock.Unlock()
for l.count == 0 {
l.takeCond.Wait()
}
if l.head == nil {
success = false
return
}
value = l.head.val
success = true
l.head = l.head.next
l.count--
l.putCond.Signal()
return
}