forked from Terry-Mao/goim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
94 lines (85 loc) · 1.83 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"sync"
)
const (
// signal command
signalNum = 1
protoFinish = 0
protoReady = 1
)
// Channel used by message pusher send msg to write goroutine.
type Channel struct {
RoomId int32
signal chan int
CliProto Ring
SvrProto Ring
cLock sync.Mutex
}
func NewChannel(cliProto, svrProto int, rid int32) *Channel {
c := new(Channel)
c.RoomId = rid
c.signal = make(chan int, signalNum)
InitRing(&c.CliProto, cliProto)
InitRing(&c.SvrProto, svrProto)
return c
}
func (c *Channel) Ready() bool {
return (<-c.signal) == protoReady
}
func (c *Channel) Signal() {
// just ignore duplication signal
select {
case c.signal <- protoReady:
default:
}
}
func (c *Channel) Finish() {
// don't use close chan, Signal can be reused
// if chan full, writer goroutine next fetch from chan will exit
// if chan empty, send a 0(close) let the writer exit
select {
case c.signal <- protoFinish:
default:
}
}
// not goroutine safe, must push one by one.
func (c *Channel) PushMsg(ver int16, operation int32, body []byte) (err error) {
var proto *Proto
c.cLock.Lock()
// fetch a proto from channel free list
if proto, err = c.SvrProto.Set(); err != nil {
c.cLock.Unlock()
return
}
proto.Ver = ver
proto.Operation = operation
proto.Body = body
c.SvrProto.SetAdv()
c.cLock.Unlock()
c.Signal()
return
}
// not goroutine safe, must push one by one.
func (c *Channel) PushMsgs(ver []int32, operations []int32, bodies [][]byte) (idx int32, err error) {
var (
proto *Proto
n int32
)
c.cLock.Lock()
for n = 0; n < int32(len(ver)); n++ {
// fetch a proto from channel free list
if proto, err = c.SvrProto.Set(); err != nil {
goto finish
}
proto.Ver = int16(ver[n])
proto.Operation = operations[n]
proto.Body = bodies[n]
c.SvrProto.SetAdv()
idx = n
}
finish:
c.cLock.Unlock()
c.Signal()
return
}