Deviopath › Go

Stop on Cancel

Hard · Concurrency

context.Context carries cancellation. SumUntil(ctx, nums) adds numbers until ctx is done, then returns the total so far. Check ctx.Done() in a select with a default, or between items.

RunSum(nums, cancelAfter) is already written: it cancels after cancelAfter items by using a context that is canceled from another goroutine once that many have been observed. To keep tests deterministic, cancelAfter of -1 means never cancel, and the implementation should just sum everything when the context is never canceled.

Write SumUntil(ctx, nums) that stops early if ctx.Err() != nil before adding an item.

Next: sync.Once