WithCancel and WithTimeout
Creating cancelable and timed contexts
context.WithCancel
WithCancel derives a new context with a cancel function. Calling cancel closes the Done channel of the derived context and all its children.
ctx, cancel := context.WithCancel(parent)
defer cancel() // always call to release resources
go doWork(ctx)Always defer cancel
Failing to call cancel leaks the goroutine that monitors the parent context. Always defer cancel immediately after creating a cancellable context.
All lessons in this course
- Why context.Context Exists
- WithCancel and WithTimeout
- WithDeadline and WithValue
- Context in HTTP and Database Calls