From 8f8a2d730a20223217305dad3c894f5cc8efc8d4 Mon Sep 17 00:00:00 2001 From: sneak Date: Tue, 29 Sep 2020 17:04:16 -0700 Subject: [PATCH] hidden goroutine++ --- go/statemachine.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/go/statemachine.go b/go/statemachine.go index c22280b..8638f96 100644 --- a/go/statemachine.go +++ b/go/statemachine.go @@ -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 } }