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
WithTimeoutreturns a context and itscancel.<-ctx.Done()fires when it expires.errors.Ischecks forDeadlineExceeded.
Keywords and builtins used here
casedefererrorfuncreturnselect
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.
Step 1 of 3 in Context, step 11 of 25 in Concurrency.