-
Notifications
You must be signed in to change notification settings - Fork 0
/
conditional.go
78 lines (65 loc) · 1.96 KB
/
conditional.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
package dmon
// Conditional ...
type Conditional struct {
cid string
monitor *Monitor
signalChan chan bool
waiting []string
}
func newConditional(mon *Monitor, cid string) *Conditional {
cond := Conditional{
cid: cid,
monitor: mon,
signalChan: make(chan bool),
waiting: []string{},
}
return &cond
}
// Wait waits on Conditional variables
func (cond *Conditional) Wait() {
cond.monitor.local.Lock()
if stringIndex(cond.waiting, cond.monitor.env.address) == -1 {
cond.waiting = append(cond.waiting, cond.monitor.env.address)
}
cond.monitor.local.Unlock()
cond.monitor.Exit()
<-cond.signalChan
cond.monitor.Enter()
cond.monitor.local.Lock()
cond.waiting = removeStringFromSlice(cond.waiting, cond.monitor.env.address)
cond.monitor.local.Unlock()
}
// Notify sends signal message to one of the processes waiting on Conditional variable
func (cond *Conditional) Notify() {
cond.monitor.local.Lock()
if len(cond.waiting) > 0 {
waitingAddress := cond.waiting[0]
if waitingAddress == cond.monitor.env.address {
cond.signalChan <- true
} else {
cond.monitor.lastSignaled = append(cond.monitor.lastSignaled, waitingAddress)
signalMsg, _ := serializeConditionalSignalMessage(cond.monitor.mid, cond.cid)
cond.monitor.env.send(waitingAddress, signalMsg)
}
}
cond.monitor.local.Unlock()
}
// NotifyAll sends signal message to all of the processes waiting on Conditional variable
func (cond *Conditional) NotifyAll() {
cond.monitor.local.Lock()
for _, addr := range cond.waiting {
if addr == cond.monitor.env.address {
cond.signalChan <- true
} else {
cond.monitor.lastSignaled = append(cond.monitor.lastSignaled, addr)
signalMsg, _ := serializeConditionalSignalMessage(cond.monitor.mid, cond.cid)
cond.monitor.env.send(addr, signalMsg)
}
}
cond.monitor.local.Unlock()
}
func (cond *Conditional) receiveSignal() {
if stringIndex(cond.waiting, cond.monitor.env.address) != -1 {
cond.signalChan <- true
}
}