Created
June 6, 2021 20:32
-
-
Save ryanc414/d0fc8d4e91539476851220eadca7331f to your computer and use it in GitHub Desktop.
Run 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 | |
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