Skip to content

Commit

Permalink
Merge pull request #1 from Code-Hex/add/stateNotify
Browse files Browse the repository at this point in the history
added stateNotify
  • Loading branch information
Code-Hex authored Dec 10, 2020
2 parents 238a11b + 9dc253a commit 22495d2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
2 changes: 2 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ func main() {
for {
select {
case <-t.C:
case newState := <-vm.StateChangedNotify():
log.Println(
"newState:", newState,
"state:", vm.State(),
"canStart:", vm.CanStart(),
"canResume:", vm.CanResume(),
Expand Down
21 changes: 18 additions & 3 deletions virtualization.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ type VirtualMachine struct {

type (
machineStatus struct {
state VirtualMachineState
state VirtualMachineState
stateNotify chan VirtualMachineState

mu sync.RWMutex
}
Expand Down Expand Up @@ -104,7 +105,8 @@ func NewVirtualMachine(config *VirtualMachineConfiguration) *VirtualMachine {
cs := charWithGoString(id)
defer cs.Free()
statuses[id] = &machineStatus{
state: VirtualMachineState(0),
state: VirtualMachineState(0),
stateNotify: make(chan VirtualMachineState),
}
handlers[id] = &machineHandlers{
start: func(error) {},
Expand Down Expand Up @@ -137,7 +139,10 @@ func changeStateOnObserver(state C.int, cID *C.char) {
// if caused panic, that's unexpected behavior.
v, _ := statuses[id.String()]
v.mu.Lock()
v.state = VirtualMachineState(state)
newState := VirtualMachineState(state)
v.state = newState
// for non-blocking
go func() { v.stateNotify <- newState }()
statuses[id.String()] = v
v.mu.Unlock()
}
Expand All @@ -152,6 +157,16 @@ func (v *VirtualMachine) State() VirtualMachineState {
return val.state
}

// StateChangedNotify gets notification is changed execution state of the virtual machine.
func (v *VirtualMachine) StateChangedNotify() <-chan VirtualMachineState {
// I expected it will not cause panic.
// if caused panic, that's unexpected behavior.
val, _ := statuses[v.id]
val.mu.RLock()
defer val.mu.RUnlock()
return val.stateNotify
}

// CanStart returns true if the machine is in a state that can be started.
func (v *VirtualMachine) CanStart() bool {
return bool(C.vmCanStart(v.Ptr(), v.dispatchQueue))
Expand Down

0 comments on commit 22495d2

Please sign in to comment.