Skip to content

Commit 22495d2

Browse files
authored
Merge pull request #1 from Code-Hex/add/stateNotify
added stateNotify
2 parents 238a11b + 9dc253a commit 22495d2

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

example/main.go

+2
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,9 @@ func main() {
145145
for {
146146
select {
147147
case <-t.C:
148+
case newState := <-vm.StateChangedNotify():
148149
log.Println(
150+
"newState:", newState,
149151
"state:", vm.State(),
150152
"canStart:", vm.CanStart(),
151153
"canResume:", vm.CanResume(),

virtualization.go

+18-3
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ type VirtualMachine struct {
7676

7777
type (
7878
machineStatus struct {
79-
state VirtualMachineState
79+
state VirtualMachineState
80+
stateNotify chan VirtualMachineState
8081

8182
mu sync.RWMutex
8283
}
@@ -104,7 +105,8 @@ func NewVirtualMachine(config *VirtualMachineConfiguration) *VirtualMachine {
104105
cs := charWithGoString(id)
105106
defer cs.Free()
106107
statuses[id] = &machineStatus{
107-
state: VirtualMachineState(0),
108+
state: VirtualMachineState(0),
109+
stateNotify: make(chan VirtualMachineState),
108110
}
109111
handlers[id] = &machineHandlers{
110112
start: func(error) {},
@@ -137,7 +139,10 @@ func changeStateOnObserver(state C.int, cID *C.char) {
137139
// if caused panic, that's unexpected behavior.
138140
v, _ := statuses[id.String()]
139141
v.mu.Lock()
140-
v.state = VirtualMachineState(state)
142+
newState := VirtualMachineState(state)
143+
v.state = newState
144+
// for non-blocking
145+
go func() { v.stateNotify <- newState }()
141146
statuses[id.String()] = v
142147
v.mu.Unlock()
143148
}
@@ -152,6 +157,16 @@ func (v *VirtualMachine) State() VirtualMachineState {
152157
return val.state
153158
}
154159

160+
// StateChangedNotify gets notification is changed execution state of the virtual machine.
161+
func (v *VirtualMachine) StateChangedNotify() <-chan VirtualMachineState {
162+
// I expected it will not cause panic.
163+
// if caused panic, that's unexpected behavior.
164+
val, _ := statuses[v.id]
165+
val.mu.RLock()
166+
defer val.mu.RUnlock()
167+
return val.stateNotify
168+
}
169+
155170
// CanStart returns true if the machine is in a state that can be started.
156171
func (v *VirtualMachine) CanStart() bool {
157172
return bool(C.vmCanStart(v.Ptr(), v.dispatchQueue))

0 commit comments

Comments
 (0)