Skip to content

Latest commit

 

History

History
73 lines (55 loc) · 2.53 KB

concurrency.cancellation.md

File metadata and controls

73 lines (55 loc) · 2.53 KB

Overview

  1. How to handle cancellation
  2. See also context doc

Key Concepts

  1. Use context for cancellation
  2. Parent context cancels children (Propagation)
    1. child context does NOT cancel parent context
    2. eg. context.Background() is never cancelled
  3. HTTP Server: automatically cancels context when connection closed
  4. HTTP Client: Use http.NewRequestWithContext or req.WithContext to handle cancellation
  5. Cancellation is cooperative, cancellation does NOT kill a goroutine
  6. go vet checks that CancelFuncs are used on all control-flow paths.

Idioms

  1. Call cancel() func in defer statement
  2. Always call cancel() func returned by WithDeadline or WithCancel

Examples

Example: Cancel manually

func foo() {
    parentCtx := context.Background()
    ...

    ctx, cancel = context.WithCancel(parentCtx) // context.WithDeadline is similar
    defer cancel() // Guarantee child cancellation

    // pass ctx to another func or use below
    // (eg. pass to http client, grpc client, sql client, kafka, rabbitmq client, ...)
}

Example: Listen for cancellation (Cancel aware task)

  1. To handle cancellation, timeout, deadline expiration:
type FooResult int // or a struct with both result & error

func DoSomeExpensiveIO(ctx context.Context) (FooResult, error) {

    // result of "real" call goes into channel
    // sender not blocked since buffer is 1
    resultCh := make(chan FooResult, 1)

    go func() {
        // send returned result to channel
        resultCh <- doRealIOWork()

        // -- alternative: func writes result to channel (instead of returning)
        // doRealIOWork(resultCh)
    }()

    // wait for first of [a result] or [cancellation/timeout]
    select {
    case <-ctx.Done():
        return 0, ctx.Err()

    case out := <-resultCh:
        return out, nil
    }
}

Other Resources

  1. https://go.dev/doc/database/cancel-operations
  2. https://www.prakharsrivastav.com/posts/golang-context-and-cancellation/
  3. https://www.sohamkamani.com/golang/context-cancellation-and-values/
  4. https://medium.com/a-journey-with-go/go-context-and-cancellation-by-propagation-7a808bbc889c