Update context example

This commit is contained in:
Fedor Korotkiy 2023-03-18 13:08:52 +04:00
parent 77d0dffbbf
commit d4dbfa776e
2 changed files with 5 additions and 1 deletions

View file

@ -35,7 +35,7 @@ func doSlowJob(ctx context.Context) error {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return ctx.Err() return context.Cause(ctx)
default: default:
// perform a portion of slow job // perform a portion of slow job
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)

View file

@ -372,6 +372,10 @@ Concurrency with Shared Memory
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
defer cancel() defer cancel()
// manual cancel with explicit cause
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(fmt.Errorf("job not needed"))
// cancel by timeout // cancel by timeout
ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel() defer cancel()