-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: context: WithInterrupt for lower overhead checking of cancellation #72040
Comments
WithInterrupt
to context
Package
It seems you can do this with just var b atomic.Bool
context.AfterFunc(ctx, func() { b.Store(true) })
for {
if b.Load() {
_ = ctx.Err()
}
} That is, does this really need to be in the standard library? https://go.dev/doc/faq#x_in_std |
If this is a performance hack, could you provide a comparison of timings, ideally a CPU profile? I wonder why the ordinary channel poll operation is too slow, and whether it could simply be made faster. A
and then does an atomic load. The last two could in principle be eliminated statically by the compiler. The rest seem truly dynamic, albeit fairly predictable branches. |
Related Issues
Related Documentation (Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.) |
As @seankhliao says, it seems that you can do exactly this today with Also, |
FWIW, on my M1 MacBook an Selecting on So |
Change https://go.dev/cl/653795 mentions this issue: |
Proposal Details
Abstract
This proposal introduces
WithInterrupt
, a new function in thecontext
package that provides an atomic-based, low-overhead cancellation check for performance-sensitive code.Background
The
context
package provides mechanisms for request-scoped cancellation, by checkingctx.Err()
or<-ctx.Done()
, but in tight loops these can introduce significant overhead.A common workaround is to periodically check
ctx.Err()
using a counter rather than in every iteration, but this introduces a trade-off between responsiveness and efficiency. A better approach is to usesync/atomic
to maintain a separate cancellation flag, but this both a non-obvious solution and must be implemented manually each time, though this code isn't that difficult to write once you understand the problem.Proposal
Add
WithInterrupt
to thecontext
package (implementation as an example)Use Case Example
The text was updated successfully, but these errors were encountered: