CodeBlanks Logo Icon CodeBlanks

WithCancel

Learn cancellable context with WithCancel.

WithCancel

context.WithCancel(parent) returns a child context and a cancel function. Calling cancel() cancels the child and every context derived from it; the parent is unaffected.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()  // avoid leaking resources

go izle(ctx)
// ...
cancel()  // the izle goroutine stops

cancel can be called more than once; calls after the first have no effect.

A goroutine listening for cancellation

A long-running goroutine checks for cancellation on every loop iteration:

func izle(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("durdu:", ctx.Err())
            return
        case <-time.After(100 * time.Millisecond):
            fmt.Println("kontrol")
        }
    }
}

Cancellation is cooperative: the context doesn't force the goroutine to stop; the goroutine checks the signal and exits on its own.

Practice Cancel it

Create a context with WithCancel. A goroutine waits on <-ctx.Done() and sends ctx.Err() to a channel. main calls cancel() and prints the value from the channel.

Starter code

main.go
package main

import (
    "context"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "context"
    "fmt"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    sonuc := make(chan error)
    go func() {
        <-ctx.Done()
        sonuc <- ctx.Err()
    }()
    cancel()
    fmt.Println(<-sonuc)
}

Expected output

context canceled

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if <code>cancel</code> is never called?

  • The context cancels itself
  • The context and linked resources stay in memory until the parent is cancelled Correct answer
  • Nothing
  • The program crashes

Explanation: That's why go vet warns "the cancel function is not used"; defer cancel() should be a habit.

2 Release resources

Question
ctx, cancel := context.WithCancel(ctx)
____ cancel()
Answer
ctx, cancel := context.WithCancel(ctx)
defer cancel()

Explanation: defer cancel() frees the resources tied to the context when the function ends.

3 Cancellation chain

Term Meaning
cancel() Cancels child contexts
Parent context Unaffected
ctx.Err() context.Canceled
select + Done Listens for cancellation

All lessons in Intermediate