hidden goroutine++

This commit is contained in:
Jeffrey Paul 2020-09-29 17:04:16 -07:00
parent f251c538a5
commit 8f8a2d730a
1 changed files with 23 additions and 1 deletions

View File

@ -6,6 +6,19 @@ package main
type fooReq 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 {
state string
fooc chan fooReq
@ -19,6 +32,14 @@ func (sm *stateMachine) foo() int {
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() {
for {
select {
@ -26,7 +47,8 @@ func (sm *stateMachine) loop() {
sm.handleFoo(r)
case r := <-sm.barc:
sm.handleBar(r)
case: <-sm.quitc:
case: q := <-sm.quitc:
close(q)
return
}
}