-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathqueue.go
79 lines (64 loc) · 1.16 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
package main
import "sync"
// TODO: Make this an interface and multiple implementations (Redis etc?)
type Queue struct {
sync.Mutex
storage []string
filter func(string) *string
count int
cond *sync.Cond
done <-chan struct{}
}
func NewQueue(filter func(string) *string, done <-chan struct{}) *Queue {
q := Queue{
storage: []string{},
filter: filter,
done: done,
}
q.cond = sync.NewCond(&q)
return &q
}
func (q *Queue) Add(item string) bool {
q.Lock()
r := q.filter(item)
if r == nil {
q.Unlock()
return false
}
q.storage = append(q.storage, *r)
q.count++
q.Unlock()
q.cond.Signal()
return true
}
func (q *Queue) Iter() <-chan string {
ch := make(chan string)
go func() {
<-q.done
q.cond.Signal() // Wake up to close the channel.
}()
go func() {
for {
q.Lock()
if len(q.storage) == 0 {
// Wait until next Add
q.cond.Wait()
if len(q.storage) == 0 {
// Queue is finished
close(ch)
q.Unlock()
return
}
}
r := q.storage[0]
q.storage = q.storage[1:]
q.Unlock()
ch <- r
}
}()
return ch
}
func (q *Queue) Count() int {
// Number of outputs produced.
return q.count
}