AlgoMaster Logo

context.WithCancel

Last Updated: May 22, 2026

High Priority
6 min read

context.WithCancel is the simplest way to give a goroutine a stop button. You hand it a parent context and it gives you back a child context plus a cancel function. Calling cancel closes the child's Done channel, which is how any goroutine listening on that channel learns it should bail out. This chapter walks through the signature, the discipline around the cancel function, how cancellation propagates through a tree of contexts, and the classic mistakes that turn cancellation into a goroutine leak.

Premium Content

Subscribe to unlock full access to this content and more premium articles.