-
Notifications
You must be signed in to change notification settings - Fork 14
/
chan.go
82 lines (70 loc) · 1.66 KB
/
chan.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
// Copyright Contributors to the Mir project
//
// SPDX-License-Identifier: Apache-2.0
package testsim
import (
"sync"
)
// Chan represents a channel for synchronization and communication
// between processes in the simulated runtime.
type Chan struct {
lock sync.Mutex
recvProcs []*Process
recvChans []chan any
sendProcs []*Process
sendChans []chan any
}
// NewChan creates a new channel in the simulation runtime.
func NewChan() *Chan {
return &Chan{}
}
// send performs the Send operation by the process on the channel.
func (c *Chan) send(p *Process, v any) (ok bool) {
var ch chan any
c.lock.Lock()
if len(c.recvProcs) > 0 {
ch = c.recvChans[0]
c.recvProcs[0].activate()
c.recvProcs[0], c.recvProcs = nil, c.recvProcs[1:]
c.recvChans[0], c.recvChans = nil, c.recvChans[1:]
} else {
ch = make(chan any)
c.sendChans = append(c.sendChans, ch)
c.sendProcs = append(c.sendProcs, p)
p.deactivate()
}
c.lock.Unlock()
select {
case ch <- v:
return true
case <-p.killChan:
return false
case <-p.Runtime.stopChan:
return false
}
}
// recv performs the Recv operation by the process on the channel.
func (c *Chan) recv(p *Process) (v any, ok bool) {
var ch chan any
c.lock.Lock()
if len(c.sendProcs) > 0 {
ch = c.sendChans[0]
c.sendProcs[0].activate()
c.sendProcs[0], c.sendProcs = nil, c.sendProcs[1:]
c.sendChans[0], c.sendChans = nil, c.sendChans[1:]
} else {
ch = make(chan any)
c.recvChans = append(c.recvChans, ch)
c.recvProcs = append(c.recvProcs, p)
p.deactivate()
}
c.lock.Unlock()
select {
case v = <-ch:
return v, true
case <-p.killChan:
return nil, false
case <-p.Runtime.stopChan:
return nil, false
}
}