-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchannel.go
76 lines (69 loc) · 1.27 KB
/
channel.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 goutils
import (
"sync"
"time"
)
type Channel struct {
exitCh chan struct{}
mx sync.Mutex
cache []interface{}
cache2 []interface{}
fullNum int
FullChan chan struct{}
isNoticed bool
}
func NewChannel(fullNum int, interval time.Duration) *Channel {
c := &Channel{
fullNum: fullNum,
cache: make([]interface{}, 0, fullNum*2),
cache2: make([]interface{}, 0, fullNum*2),
FullChan: make(chan struct{}),
exitCh: make(chan struct{}),
}
exitCh := c.exitCh
go func() {
for {
select {
case <-exitCh:
return
default:
time.Sleep(interval)
if len(c.cache) > 0 {
c.FullChan <- struct{}{}
}
}
}
}()
return c
}
func (c *Channel) Add(msg ...interface{}) {
var needNotice bool
c.mx.Lock()
c.cache = append(c.cache, msg...)
needNotice = len(c.cache) >= c.fullNum && !c.isNoticed
if needNotice {
c.isNoticed = true
}
c.mx.Unlock()
if needNotice {
c.FullChan <- struct{}{}
}
}
func (c *Channel) Get() (ret []interface{}) {
c.mx.Lock()
c.cache, c.cache2 = c.cache2, c.cache
c.cache = c.cache[:0]
c.isNoticed = false
c.mx.Unlock()
return c.cache2
}
func (c *Channel) Len() int {
c.mx.Lock()
l := len(c.cache)
c.mx.Unlock()
return l
}
func (c *Channel) Close() error {
close(c.exitCh)
return nil
}