User Tools

Site Tools


go:concurrency:cancel

WithCancel

What is it?

`context.WithCancel(parent)` creates a child context that can be canceled manually by calling the returned `cancel()` function.

Signature: `ctx, cancel := context.WithCancel(parent)`

What is it used for?

  • Stop background goroutines when you’re done.
  • Cancel a group of tasks if one fails.
  • Implement graceful shutdown logic.

Example

ctx, cancel := context.WithCancel(context.Background())
go func() {
    <-ctx.Done()
    // cleanup or stop work
}()
cancel()

Notes / pitfalls

  • Always call `cancel()` to release resources.
  • Cancellation propagates: canceling parent cancels children.
  • Use `select { case ←ctx.Done(): … }` inside goroutines.

Hard words (English)

  • manual /ˈmænjuəl/: thủ công
  • cleanup /ˈkliːnʌp/: dọn dẹp tài nguyên
  • propagate /ˈprɑːpəɡeɪt/: truyền tiếp
  • graceful shutdown /ˈɡreɪsfəl ˈʃʌtdaʊn/: tắt êm
go/concurrency/cancel.txt · Last modified: by phong2018