forked from pallat/queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
50 lines (42 loc) · 925 Bytes
/
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
package queue
// Simpler is the represent of your items, You just make you type with 2 methods
// Len() return the number of your items and Pop return each item by index
type Simpler interface {
Pop(i int) interface{}
Len() int
}
func NewQueue(s Simpler) *Queue {
ch := make(chan int, s.Len())
for i := 0; i < s.Len(); i++ {
ch <- i
}
close(ch)
q := &Queue{
i: ch,
pop: make(chan interface{}),
emptyNotify: make(chan struct{}),
s: s,
}
go q.background()
return q
}
type Queue struct {
i chan int
pop chan interface{}
emptyNotify chan struct{}
s Simpler
}
func (q *Queue) background() {
defer close(q.pop)
defer close(q.emptyNotify)
for i := range q.i {
q.pop <- q.s.Pop(i)
}
q.emptyNotify <- struct{}{}
}
func (q *Queue) Pop() <-chan interface{} {
return q.pop
}
func (q *Queue) Empty() <-chan struct{} {
return q.emptyNotify
}