typestar

Context and cancellation in Go

Propagating deadlines and cancellation signals.

func work(ctx context.Context, d time.Duration) error {
    select {
    case <-time.After(d):
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

func run() error {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    return work(ctx, 2*time.Second)
}

How it works

  1. WithTimeout returns a context and its cancel.
  2. <-ctx.Done() fires when it expires.
  3. errors.Is checks for DeadlineExceeded.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
276
Tokens
84
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 48 seconds.

Type this snippet

Step 1 of 3 in Context, step 11 of 25 in Concurrency.

← Previous Next →