Created
June 6, 2021 20:31
-
-
Save ryanc414/cff276344d909dab859bd125a1efbfe5 to your computer and use it in GitHub Desktop.
Start-Closer pattern in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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