-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
107 lines (94 loc) · 1.88 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"sync"
"sync/atomic"
)
type queueItem struct {
ID int64
tr transaction
result chan string
}
type queue struct {
items []*queueItem
mutex sync.Mutex
maxSize int64
addChan chan *queueItem
stopChan chan struct{}
wg sync.WaitGroup
nextID int64
}
func newQueue(maxSize int64) *queue {
if maxSize <= 0 {
maxSize = 8192
}
queue := &queue{
items: make([]*queueItem, 0, maxSize),
maxSize: maxSize,
addChan: make(chan *queueItem),
stopChan: make(chan struct{}),
nextID: 0,
}
queue.wg.Add(1)
go queue.processItems()
return queue
}
func (q *queue) Add(tr transaction) (int64, <-chan string) {
q.mutex.Lock()
defer q.mutex.Unlock()
if int64(len(q.items)) >= q.maxSize {
removedItem := q.items[0]
q.items = q.items[1:]
close(removedItem.result)
}
id := atomic.AddInt64(&q.nextID, 1)
tr.id = id
resultChan := make(chan string, 1)
item := &queueItem{
ID: id,
tr: tr,
result: resultChan,
}
q.items = append(q.items, item)
q.addChan <- item
return id, resultChan
}
func (q *queue) Remove(id int64) {
q.mutex.Lock()
defer q.mutex.Unlock()
for i, item := range q.items {
if item.ID == id {
q.items = append(q.items[:i], q.items[i+1:]...)
break
}
}
}
func (q *queue) processItems() {
defer q.wg.Done()
for {
select {
case item := <-q.addChan:
result := item.tr.execute()
item.result <- result
close(item.result)
q.mutex.Lock()
for i, qItem := range q.items {
if qItem.ID == item.ID {
q.items = append(q.items[:i], q.items[i+1:]...)
break
}
}
q.mutex.Unlock()
case <-q.stopChan:
return
}
}
}
func (q *queue) Stop() {
close(q.stopChan)
q.wg.Wait()
q.mutex.Lock()
defer q.mutex.Unlock()
for _, item := range q.items {
close(item.result)
}
}