-
Notifications
You must be signed in to change notification settings - Fork 4
/
cmd.go
76 lines (60 loc) · 1 KB
/
cmd.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 scp
import (
"context"
"sync"
)
// Commands for the Node goroutine.
type Cmd interface{}
type msgCmd struct {
msg *Msg
}
type deferredUpdateCmd struct {
slot *Slot
}
type newRoundCmd struct {
slot *Slot
}
type rehandleCmd struct {
slot *Slot
}
type delayCmd struct {
ms int
}
// Internal channel for queueing and processing commands.
type cmdChan struct {
cond sync.Cond
cmds []Cmd
}
func newCmdChan() *cmdChan {
result := new(cmdChan)
result.cond.L = new(sync.Mutex)
return result
}
func (c *cmdChan) write(cmd Cmd) {
c.cond.L.Lock()
c.cmds = append(c.cmds, cmd)
c.cond.Broadcast()
c.cond.L.Unlock()
}
func (c *cmdChan) read(ctx context.Context) (Cmd, bool) {
c.cond.L.Lock()
defer c.cond.L.Unlock()
for len(c.cmds) == 0 {
ch := make(chan struct{})
go func() {
c.cond.Wait()
close(ch)
}()
select {
case <-ctx.Done():
return nil, false
case <-ch:
if len(c.cmds) == 0 {
continue
}
}
}
result := c.cmds[0]
c.cmds = c.cmds[1:]
return result, true
}