andrey mirtchovski
unread,Feb 16, 2018, 4:05:50 PM2/16/18Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to golang-nuts
While trying to retrofit context.Context within a
worker-pool-patterned package, where work is sent down a channel to be
picked up by number of worker goroutines.
I'm running against the mantra of "Do not store Contexts inside a struct type".
For example, I want to put a timeout on the amount of time spent
waiting to write on a channel, plus the time it takes for my write to
be consumed on the other end (the time the requests spends enqueued on
the channel buffer). How would I go about doing that without embedding
a context.Context inside my write?
A typical example, here is how i would do it without the channel send:
func p(ctx context.Context, req Request) {
ctx, _ = context.WithTimeout(ctx, Timeout)
select {
case <-ctx.Done:
// timed out
default:
worker(ctx, req) // will use ctx to determine if timeout expired
}
}
With a channel I may do something like:
func c(req Request, in chan Request) {
in <- req
<-out
}
func worker(in chan Request) {
for _, v := range in {
// i want to cancel here if 'v' has lived past its timeout
// or do work if not
}
}
And I want to have a meaningful way to measure enqueue time before req
is consumed by a worker in the second example.
Hopefully that makes sense.