hidden goroutine++
This commit is contained in:
parent
f251c538a5
commit
8f8a2d730a
@ -6,6 +6,19 @@ package main
|
|||||||
type fooReq struct{}
|
type fooReq struct{}
|
||||||
type barReq struct{}
|
type barReq struct{}
|
||||||
|
|
||||||
|
// really though this should take a context, pass it to loop(),
|
||||||
|
// and select on ctx.Done()
|
||||||
|
func NewStateMachine() *stateMachine {
|
||||||
|
sm := &stateMachine{
|
||||||
|
state: "initial",
|
||||||
|
fooc: make(chan fooReq),
|
||||||
|
barc: make(chan fooReq),
|
||||||
|
quitc: make(chan chan struct{}),
|
||||||
|
}
|
||||||
|
go sm.loop()
|
||||||
|
return sm
|
||||||
|
}
|
||||||
|
|
||||||
type stateMachine struct {
|
type stateMachine struct {
|
||||||
state string
|
state string
|
||||||
fooc chan fooReq
|
fooc chan fooReq
|
||||||
@ -19,6 +32,14 @@ func (sm *stateMachine) foo() int {
|
|||||||
return <-c
|
return <-c
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (sm *stateMachine) stop() {
|
||||||
|
q := make(chan struct{})
|
||||||
|
sm.quitc <- q
|
||||||
|
|
||||||
|
// block return until the select in loop() hits
|
||||||
|
<-q
|
||||||
|
}
|
||||||
|
|
||||||
func (sm *stateMachine) loop() {
|
func (sm *stateMachine) loop() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@ -26,7 +47,8 @@ func (sm *stateMachine) loop() {
|
|||||||
sm.handleFoo(r)
|
sm.handleFoo(r)
|
||||||
case r := <-sm.barc:
|
case r := <-sm.barc:
|
||||||
sm.handleBar(r)
|
sm.handleBar(r)
|
||||||
case: <-sm.quitc:
|
case: q := <-sm.quitc:
|
||||||
|
close(q)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user