Skip to content

Instantly share code, notes, and snippets.

@ryanc414
Created June 6, 2021 20:32
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/d0fc8d4e91539476851220eadca7331f to your computer and use it in GitHub Desktop.
Save ryanc414/d0fc8d4e91539476851220eadca7331f to your computer and use it in GitHub Desktop.
Run pattern in Go
func run(ctx context.Context) error {
var h Handler
ctx, cancel := context.WithCancel(ctx)
var wg sync.WaitGroup
wg.Add(1)
go func() {
h.Run(ctx)
wg.Done()
}()
defer func() {
cancel()
wg.Wait()
}()
for i := 0; i < 10; i++ {
select {
case <-time.After(time.Second):
log.Print(h.GetVal())
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
type Handler struct {
val int
mu sync.Mutex
}
func (h *Handler) Run(ctx context.Context) error {
log.Print("Starting handler")
for {
select {
case <-time.After(100 * time.Millisecond):
h.mu.Lock()
h.val = rand.Int()
h.mu.Unlock()
case <-ctx.Done():
log.Print("exiting handler")
return ctx.Err()
}
}
}
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