Skip to content

Instantly share code, notes, and snippets.

@ryanc414
Created June 6, 2021 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanc414/cff276344d909dab859bd125a1efbfe5 to your computer and use it in GitHub Desktop.
Save ryanc414/cff276344d909dab859bd125a1efbfe5 to your computer and use it in GitHub Desktop.
Start-Closer pattern in Go
func run(ctx context.Context) error {
var h Handler
h.Start(ctx)
defer h.Close()
for i := 0; i < 10; i++ {
select {
case <-time.After(time.Second):
log.Print(h.GetVal())
case <-ctx.Done():
return ctx.Err()
}
}
log.Print("exiting")
return nil
}
type Handler struct {
val int
mu sync.Mutex
wg sync.WaitGroup
cancel context.CancelFunc
}
func (h *Handler) Start(ctx context.Context) {
log.Print("Starting handler")
ctx, h.cancel = context.WithCancel(ctx)
h.wg.Add(1)
go func() {
for {
select {
case <-time.After(100 * time.Millisecond):
h.mu.Lock()
h.val = rand.Int()
h.mu.Unlock()
case <-ctx.Done():
h.wg.Done()
return
}
}
}()
}
func (h *Handler) Close() {
h.cancel()
h.wg.Wait()
log.Print("Handler closed")
}
func (h *Handler) GetVal() int {
h.mu.Lock()
defer h.mu.Unlock()
return h.val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment