-
Notifications
You must be signed in to change notification settings - Fork 882
/
pipe.go
71 lines (53 loc) · 1.12 KB
/
pipe.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
package cellnet
import (
"sync"
)
// 不限制大小,添加不发生阻塞,接收阻塞等待
type Pipe struct {
list []interface{}
listGuard sync.Mutex
listCond *sync.Cond
}
// 添加时不会发送阻塞
func (self *Pipe) Add(msg interface{}) {
self.listGuard.Lock()
self.list = append(self.list, msg)
self.listGuard.Unlock()
self.listCond.Signal()
}
func (self *Pipe) Count() int {
self.listGuard.Lock()
defer self.listGuard.Unlock()
return len(self.list)
}
func (self *Pipe) Reset() {
self.listGuard.Lock()
self.list = self.list[0:0]
self.listGuard.Unlock()
}
// 如果没有数据,发生阻塞
func (self *Pipe) Pick(retList *[]interface{}) (exit bool) {
self.listGuard.Lock()
for len(self.list) == 0 {
self.listCond.Wait()
}
// self.listGuard.Unlock()
// self.listGuard.Lock()
// 复制出队列
for _, data := range self.list {
if data == nil {
exit = true
break
} else {
*retList = append(*retList, data)
}
}
self.list = self.list[0:0]
self.listGuard.Unlock()
return
}
func NewPipe() *Pipe {
self := &Pipe{}
self.listCond = sync.NewCond(&self.listGuard)
return self
}