取消與逾時

最後更新


用 WithCancel、WithTimeout、WithDeadline 讓工作能被中止,用 WithCancelCause 記錄中止原因,用 AfterFunc 在取消時執行清理。

衍生可取消的 context


context 基礎介紹過,Background() 永遠不會被取消。要讓工作可以喊停,就從它(或任何既有的 context)衍生出新的 context:
函式何時被取消加入版本
WithCancel呼叫回傳的 cancel
WithTimeout經過指定時間,或呼叫 cancel
WithDeadline到達指定時刻,或呼叫 cancel
WithCancelCause呼叫 cancel(err),並記錄原因Go 1.20 起
WithTimeoutCause / WithDeadlineCause逾時時記錄指定原因Go 1.21 起
AfterFunc不產生新 context,而是在取消時呼叫函式Go 1.21 起

不論哪一種,父 context 被取消時,衍生的子 context 也一定會被取消。

WithCancel


手動取消一群 goroutine


WithCancel 回傳一個子 context 和一個 cancel 函式。呼叫 cancel 會關閉子 context 的 Done channel,所有監聽它的 goroutine 都會收到通知。
簽名:
  1. func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. )
  7. func worker(ctx context.Context, id int, jobs <-chan int, done []int) {
  8. for {
  9. select {
  10. case <-ctx.Done():
  11. return
  12. case _, ok := <-jobs:
  13. if !ok {
  14. return
  15. }
  16. done[id]++
  17. }
  18. }
  19. }
  20. func main() {
  21. ctx, cancel := context.WithCancel(context.Background())
  22. defer cancel()
  23. jobs := make(chan int)
  24. done := make([]int, 3)
  25. var wg sync.WaitGroup
  26. for id := range 3 {
  27. wg.Go(func() {
  28. worker(ctx, id, jobs, done)
  29. })
  30. }
  31. for i := range 9 {
  32. jobs <- i
  33. }
  34. cancel()
  35. wg.Wait()
  36. total := 0
  37. for _, n := range done {
  38. total += n
  39. }
  40. fmt.Println("處理完成的工作數:", total)
  41. fmt.Println("ctx.Err():", ctx.Err())
  42. }

輸出:
  1. 處理完成的工作數: 9
  2. ctx.Err(): context canceled

每個 worker 處理幾件工作取決於排程,所以這裡只印總數。cancel() 之後,三個 worker 都從 ctx.Done() 收到通知而結束,wg.Wait() 才得以回傳。

一定要呼叫 cancel


cancel 除了發出取消訊號,還會把子 context 從父 context 上解除註冊、釋放計時器等資源。就算工作正常結束,也要呼叫它;慣用寫法是拿到後立刻 defer cancel()。cancel 可以重複呼叫,第二次之後什麼都不做。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func lookup(parent context.Context, key string) string {
  7. ctx, cancel := context.WithCancel(parent)
  8. defer cancel()
  9. if ctx.Err() != nil {
  10. return "取消"
  11. }
  12. return "value-of-" + key
  13. }
  14. func main() {
  15. fmt.Println(lookup(context.Background(), "a"))
  16. ctx, cancel := context.WithCancel(context.Background())
  17. cancel()
  18. cancel()
  19. fmt.Println("重複取消後:", ctx.Err())
  20. fmt.Println(lookup(ctx, "b"))
  21. }

輸出:
  1. value-of-a
  2. 重複取消後: context canceled
  3. 取消

注意:忘記呼叫 cancel 會讓子 context 一直掛在父 context 上,直到父 context 被取消為止,造成資源洩漏。go vet 的 lostcancel 檢查會抓出「拿到 cancel 卻沒在所有路徑呼叫」的情況。

WithTimeout 與 WithDeadline


WithTimeout:最多等這麼久


WithTimeout(parent, d) 在經過時間 d 之後自動取消。逾時時 Err() 回傳 context.DeadlineExceeded,可以用 errors.Is 判斷。
簽名:
  1. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. )
  8. func query(ctx context.Context, cost time.Duration) (string, error) {
  9. select {
  10. case <-time.After(cost):
  11. return "查詢結果", nil
  12. case <-ctx.Done():
  13. return "", ctx.Err()
  14. }
  15. }
  16. func main() {
  17. for _, cost := range []time.Duration{10 * time.Millisecond, 500 * time.Millisecond} {
  18. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  19. res, err := query(ctx, cost)
  20. cancel()
  21. fmt.Printf("耗時 %v: res=%q err=%v\n", cost, res, err)
  22. if errors.Is(err, context.DeadlineExceeded) {
  23. fmt.Println(" → 逾時")
  24. }
  25. }
  26. }

輸出:
  1. 耗時 10ms: res="查詢結果" err=<nil>
  2. 耗時 500ms: res="" err=context deadline exceeded
  3. → 逾時

time.After 在這裡模擬一個要花 cost 時間的操作。第二次查詢要 500ms,超過 100ms 的上限,就在逾時那一刻回傳錯誤,不必等到 500ms。

WithDeadline:在某個時刻之前完成


WithDeadline(parent, t) 指定的是絕對時刻而不是時間長度。WithTimeout(parent, d) 其實就等於 WithDeadline(parent, time.Now().Add(d))。當截止時間來自外部(例如請求標頭帶來的時間點)時,用 WithDeadline 比較自然。
簽名:
  1. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. func main() {
  8. deadline := time.Now().Add(50 * time.Millisecond)
  9. ctx, cancel := context.WithDeadline(context.Background(), deadline)
  10. defer cancel()
  11. d, ok := ctx.Deadline()
  12. fmt.Println("有截止時間:", ok)
  13. fmt.Println("與設定相同:", d.Equal(deadline))
  14. child, cancelChild := context.WithTimeout(ctx, time.Hour)
  15. defer cancelChild()
  16. cd, _ := child.Deadline()
  17. fmt.Println("子 context 的截止時間沿用父的:", cd.Equal(deadline))
  18. <-child.Done()
  19. fmt.Println("child:", child.Err())
  20. fmt.Println("parent:", ctx.Err())
  21. }

輸出:
  1. 有截止時間: true
  2. 與設定相同: true
  3. 子 context 的截止時間沿用父的: true
  4. child: context deadline exceeded
  5. parent: context deadline exceeded

子 context 想要一小時,但父 context 50ms 後就到期,所以子的截止時間是兩者中較早的那個。衍生的 context 只能縮短期限,不能延長。
注意:截止時間已經過去時,WithDeadline 回傳的 context 一開始就是已取消狀態,Err() 立刻回傳 DeadlineExceeded。

記錄取消原因


ctx.Err() 只會告訴你「被取消了」或「逾時了」,看不出為什麼。Go 1.20 起可以在取消時附上一個原因(cause),之後用 context.Cause(ctx) 取出。

WithCancelCause 與 Cause(Go 1.20 起)


WithCancelCause 回傳的 cancel 接受一個 error 參數。Err() 仍然回傳 context.Canceled,維持與既有程式碼相容;Cause 則回傳你傳入的那個錯誤。
簽名:
  1. func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
  2. func Cause(c Context) error

範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. )
  7. var ErrQuotaExceeded = errors.New("配額已用完")
  8. func main() {
  9. ctx, cancel := context.WithCancelCause(context.Background())
  10. fmt.Println("取消前 Cause:", context.Cause(ctx))
  11. cancel(ErrQuotaExceeded)
  12. fmt.Println("Err:", ctx.Err())
  13. fmt.Println("Cause:", context.Cause(ctx))
  14. fmt.Println("是配額問題:", errors.Is(context.Cause(ctx), ErrQuotaExceeded))
  15. child, cancelChild := context.WithCancel(ctx)
  16. defer cancelChild()
  17. fmt.Println("子 context 的 Cause:", context.Cause(child))
  18. plain, cancelPlain := context.WithCancelCause(context.Background())
  19. cancelPlain(nil)
  20. fmt.Println("傳 nil 時的 Cause:", context.Cause(plain))
  21. }

輸出:
  1. 取消前 Cause: <nil>
  2. Err: context canceled
  3. Cause: 配額已用完
  4. 是配額問題: true
  5. 子 context 的 Cause: 配額已用完
  6. 傳 nil 時的 Cause: context canceled

原因會傳給子孫 context。cancel(nil) 時原因就是 context.Canceled;對沒有設定原因的 context 呼叫 Cause,結果與 Err() 相同。

WithTimeoutCause(Go 1.21 起)


WithTimeoutCause 與 WithDeadlineCause 讓「逾時」也能帶上自訂原因,方便在錯誤訊息裡說明是哪一段超時。
簽名:
  1. func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
  2. func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. )
  8. var ErrPaymentSlow = errors.New("金流服務回應超過 30ms")
  9. func main() {
  10. ctx, cancel := context.WithTimeoutCause(context.Background(), 30*time.Millisecond, ErrPaymentSlow)
  11. defer cancel()
  12. <-ctx.Done()
  13. fmt.Println("Err:", ctx.Err())
  14. fmt.Println("Cause:", context.Cause(ctx))
  15. fmt.Println("仍可判斷為逾時:", errors.Is(ctx.Err(), context.DeadlineExceeded))
  16. }

輸出:
  1. Err: context deadline exceeded
  2. Cause: 金流服務回應超過 30ms
  3. 仍可判斷為逾時: true

注意:回傳的 cancel 不帶原因。如果在逾時之前就呼叫 cancel(),Cause 回傳的是 context.Canceled,而不是你指定的錯誤。

AfterFunc:取消時執行清理


註冊與停止(Go 1.21 起)


AfterFunc(ctx, f) 安排在 ctx 被取消後,於另一個 goroutine 執行 f。不需要自己開 goroutine 守著 ctx.Done()。它回傳一個 stop 函式,用來取消這個安排:
stop() 回傳意義
true成功阻止 f 執行
falsef 已經開始執行,或先前已經停止過

簽名:
  1. func AfterFunc(ctx Context, f func()) (stop func() bool)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func main() {
  7. ctx, cancel := context.WithCancel(context.Background())
  8. cleaned := make(chan string)
  9. context.AfterFunc(ctx, func() {
  10. cleaned <- "關閉連線、釋放暫存檔"
  11. })
  12. stop := context.AfterFunc(ctx, func() {
  13. fmt.Println("這行不會被印出")
  14. })
  15. fmt.Println("stop 成功:", stop())
  16. cancel()
  17. fmt.Println("清理:", <-cleaned)
  18. fmt.Println("取消後再 stop:", stop())
  19. done, cancelDone := context.WithCancel(context.Background())
  20. cancelDone()
  21. ran := make(chan struct{})
  22. context.AfterFunc(done, func() { close(ran) })
  23. <-ran
  24. fmt.Println("已取消的 ctx 會立刻執行 f")
  25. }

輸出:
  1. stop 成功: true
  2. 清理: 關閉連線、釋放暫存檔
  3. 取消後再 stop: false
  4. 已取消的 ctx 會立刻執行 f

注意:f 是在別的 goroutine 執行,stop 也不會等 f 跑完。如果呼叫端需要知道 f 何時完成,要像範例一樣自己用 channel 協調。

重點整理


  • WithCancel 手動取消;WithTimeout 指定時長;WithDeadline 指定時刻
  • 拿到 cancel 就 defer cancel(),即使工作正常結束也要呼叫
  • 逾時時 Err() 是 context.DeadlineExceeded,手動取消是 context.Canceled,用 errors.Is 判斷
  • 子 context 只能縮短期限,不能延長父 context 的期限
  • Go 1.20 起用 WithCancelCause 加 context.Cause 記錄取消原因,Go 1.21 起逾時也能帶原因
  • Go 1.21 起的 AfterFunc 在取消時於另一個 goroutine 執行清理,stop 可取消這個安排

資料來源