User Tools

Site Tools


go:concurrency:deadline

WithDeadline

What is it?

`context.WithDeadline(parent, t)` creates a child context that is canceled at the specific time `t` (a `time.Time`).

Signature: `ctx, cancel := context.WithDeadline(parent, t)`

What is it used for?

  • Enforce a fixed cutoff time (e.g., must finish before 10:00:05).
  • Align timeouts across multiple calls (same end time for several steps).

Example

deadline := time.Now().Add(1500 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
 
select {
case <-ctx.Done():
    // deadline exceeded or canceled
default:
    // do work
}

Notes / pitfalls

  • Always call `cancel()` to release resources.
  • If you only have a duration, `WithTimeout` is simpler.
  • Deadlines propagate to child contexts.

Hard words (English)

  • deadline /ˈdedlaɪn/: hạn chót
  • cutoff /ˈkʌtɔːf/: mốc dừng
  • align /əˈlaɪn/: căn chỉnh/đồng bộ theo cùng mốc
  • exceeded /ɪkˈsiːdɪd/: vượt quá
go/concurrency/deadline.txt · Last modified: by phong2018