Writing cancellable functions
suggest changeUsing existing functions that accept cancellable context is easy.
Writing a function that can be cancelled via context is much harder.
When a deadline expires, or you call the cancel function returned by context.WithCancel or context.WithTimeout, the channel returned by context.Done is closed.
When writing a cancellable function, periodically check that channel and return immediately if it has been closed.
The result is awkward code:
func longMathOp(ctx context.Context, n int) (int, error) {
res := n
for i := 0; i < 100; i++ {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
res += i
// simulate long operation by sleeping
time.Sleep(time.Millisecond)
}
}
return res, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*200)
defer cancel()
res, err := longMathOp(ctx, 5)
fmt.Printf("Called longMathOp() with 200ms timeout. res: %d, err: %v\n", res, err)
ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond*10)
defer cancel()
res, err = longMathOp(ctx, 5)
fmt.Printf("Called longMathOp() with 10ms timeout. res: %d, err: %v\n", res, err)
}
Called longMathOp() with 200ms timeout. res: 4955, err: <nil>
Called longMathOp() with 10ms timeout. res: 0, err: context deadline exceeded
For clarity, this is an artificial task.
longMathOp performs a simple operation 100 times and simulates slowness by sleeping for 1 ms on every iteration.
We can expect it to take ~100 ms. The sleep itself is not interrupted; cancellation is noticed on the next loop.
A select with a default clause is non-blocking. If the context is not done, ctx.Done() is not ready, so select runs the default clause immediately. That clause is where the work lives.
If the timeout is greater than about 100 ms, the function finishes.
If the timeout is smaller, ctx.Done() is closed, longMathOp notices on its next check, and it returns ctx.Err().