forked from quexer/utee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq.go
79 lines (64 loc) · 1.16 KB
/
q.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 utee
import (
"errors"
"log"
)
var ErrFull = errors.New("queue is full")
type MemQueue chan interface{}
func NewMemQueue(cap int) MemQueue {
return make(chan interface{}, cap)
}
//create memory queue, auto-leak element concurrently to worker
func NewLeakMemQueue(cap, concurrent int, worker func(interface{})) MemQueue {
q := NewMemQueue(cap)
f := func() {
for {
worker(q.Deq())
}
}
for i := 0; i < concurrent; i++ {
go f()
}
return q
}
//enqueue, block if queue is full
func (p MemQueue) EnqBlocking(data interface{}) {
p <- data
}
//enqueue, return error if queue is full
func (p MemQueue) Enq(data interface{}) error {
select {
case p <- data:
default:
return ErrFull
}
return nil
}
func (p MemQueue) Deq() interface{} {
return <-p
}
//dequeue less than n in a batch
func (p MemQueue) DeqN(n int) []interface{} {
if n <= 0 {
log.Println("[MemQueue] deqn err, n must > 0")
return nil
}
var l []interface{}
for {
select {
case data := <-p:
l = append(l, data)
if len(l) == n {
return l
}
default:
return l
}
}
}
func (p MemQueue) Len() int {
return len(p)
}
func (p MemQueue) Cap() int {
return cap(p)
}