# 取消與逾時

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

## 衍生可取消的 context

[context 基礎](/context-basics)介紹過，`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 都會收到通知。

簽名：
```go
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"fmt"
	"sync"
)

func worker(ctx context.Context, id int, jobs <-chan int, done []int) {
	for {
		select {
		case <-ctx.Done():
			return
		case _, ok := <-jobs:
			if !ok {
				return
			}
			done[id]++
		}
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	jobs := make(chan int)
	done := make([]int, 3)
	var wg sync.WaitGroup
	for id := range 3 {
		wg.Go(func() {
			worker(ctx, id, jobs, done)
		})
	}

	for i := range 9 {
		jobs <- i
	}
	cancel()
	wg.Wait()

	total := 0
	for _, n := range done {
		total += n
	}
	fmt.Println("處理完成的工作數:", total)
	fmt.Println("ctx.Err():", ctx.Err())
}
```

輸出：
```text
處理完成的工作數: 9
ctx.Err(): context canceled
```

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

### 一定要呼叫 cancel

`cancel` 除了發出取消訊號，還會把子 context 從父 context 上解除註冊、釋放計時器等資源。就算工作正常結束，也要呼叫它；慣用寫法是拿到後立刻 `defer cancel()`。`cancel` 可以重複呼叫，第二次之後什麼都不做。

範例：
```go
package main

import (
	"context"
	"fmt"
)

func lookup(parent context.Context, key string) string {
	ctx, cancel := context.WithCancel(parent)
	defer cancel()

	if ctx.Err() != nil {
		return "取消"
	}
	return "value-of-" + key
}

func main() {
	fmt.Println(lookup(context.Background(), "a"))

	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	cancel()
	fmt.Println("重複取消後:", ctx.Err())
	fmt.Println(lookup(ctx, "b"))
}
```

輸出：
```text
value-of-a
重複取消後: context canceled
取消
```

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

## WithTimeout 與 WithDeadline

### WithTimeout：最多等這麼久

`WithTimeout(parent, d)` 在經過時間 `d` 之後自動取消。逾時時 `Err()` 回傳 `context.DeadlineExceeded`，可以用 `errors.Is` 判斷。

簽名：
```go
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

func query(ctx context.Context, cost time.Duration) (string, error) {
	select {
	case <-time.After(cost):
		return "查詢結果", nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}

func main() {
	for _, cost := range []time.Duration{10 * time.Millisecond, 500 * time.Millisecond} {
		ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
		res, err := query(ctx, cost)
		cancel()

		fmt.Printf("耗時 %v: res=%q err=%v\n", cost, res, err)
		if errors.Is(err, context.DeadlineExceeded) {
			fmt.Println("  → 逾時")
		}
	}
}
```

輸出：
```text
耗時 10ms: res="查詢結果" err=<nil>
耗時 500ms: res="" err=context deadline exceeded
  → 逾時
```

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

### WithDeadline：在某個時刻之前完成

`WithDeadline(parent, t)` 指定的是**絕對時刻**而不是時間長度。`WithTimeout(parent, d)` 其實就等於 `WithDeadline(parent, time.Now().Add(d))`。當截止時間來自外部（例如請求標頭帶來的時間點）時，用 `WithDeadline` 比較自然。

簽名：
```go
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	deadline := time.Now().Add(50 * time.Millisecond)
	ctx, cancel := context.WithDeadline(context.Background(), deadline)
	defer cancel()

	d, ok := ctx.Deadline()
	fmt.Println("有截止時間:", ok)
	fmt.Println("與設定相同:", d.Equal(deadline))

	child, cancelChild := context.WithTimeout(ctx, time.Hour)
	defer cancelChild()
	cd, _ := child.Deadline()
	fmt.Println("子 context 的截止時間沿用父的:", cd.Equal(deadline))

	<-child.Done()
	fmt.Println("child:", child.Err())
	fmt.Println("parent:", ctx.Err())
}
```

輸出：
```text
有截止時間: true
與設定相同: true
子 context 的截止時間沿用父的: true
child: context deadline exceeded
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` 則回傳你傳入的那個錯誤。

簽名：
```go
func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
func Cause(c Context) error
```

範例：
```go
package main

import (
	"context"
	"errors"
	"fmt"
)

var ErrQuotaExceeded = errors.New("配額已用完")

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	fmt.Println("取消前 Cause:", context.Cause(ctx))

	cancel(ErrQuotaExceeded)
	fmt.Println("Err:", ctx.Err())
	fmt.Println("Cause:", context.Cause(ctx))
	fmt.Println("是配額問題:", errors.Is(context.Cause(ctx), ErrQuotaExceeded))

	child, cancelChild := context.WithCancel(ctx)
	defer cancelChild()
	fmt.Println("子 context 的 Cause:", context.Cause(child))

	plain, cancelPlain := context.WithCancelCause(context.Background())
	cancelPlain(nil)
	fmt.Println("傳 nil 時的 Cause:", context.Cause(plain))
}
```

輸出：
```text
取消前 Cause: <nil>
Err: context canceled
Cause: 配額已用完
是配額問題: true
子 context 的 Cause: 配額已用完
傳 nil 時的 Cause: context canceled
```

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

### WithTimeoutCause（Go 1.21 起）

`WithTimeoutCause` 與 `WithDeadlineCause` 讓「逾時」也能帶上自訂原因，方便在錯誤訊息裡說明是哪一段超時。

簽名：
```go
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

var ErrPaymentSlow = errors.New("金流服務回應超過 30ms")

func main() {
	ctx, cancel := context.WithTimeoutCause(context.Background(), 30*time.Millisecond, ErrPaymentSlow)
	defer cancel()

	<-ctx.Done()
	fmt.Println("Err:", ctx.Err())
	fmt.Println("Cause:", context.Cause(ctx))
	fmt.Println("仍可判斷為逾時:", errors.Is(ctx.Err(), context.DeadlineExceeded))
}
```

輸出：
```text
Err: context deadline exceeded
Cause: 金流服務回應超過 30ms
仍可判斷為逾時: true
```

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

## AfterFunc：取消時執行清理

### 註冊與停止（Go 1.21 起）

`AfterFunc(ctx, f)` 安排在 `ctx` 被取消後，於**另一個 goroutine** 執行 `f`。不需要自己開 goroutine 守著 `ctx.Done()`。它回傳一個 `stop` 函式，用來取消這個安排：

| `stop()` 回傳 | 意義 |
| --- | --- |
| `true` | 成功阻止 `f` 執行 |
| `false` | `f` 已經開始執行，或先前已經停止過 |

簽名：
```go
func AfterFunc(ctx Context, f func()) (stop func() bool)
```

範例：
```go
package main

import (
	"context"
	"fmt"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	cleaned := make(chan string)
	context.AfterFunc(ctx, func() {
		cleaned <- "關閉連線、釋放暫存檔"
	})

	stop := context.AfterFunc(ctx, func() {
		fmt.Println("這行不會被印出")
	})
	fmt.Println("stop 成功:", stop())

	cancel()
	fmt.Println("清理:", <-cleaned)

	fmt.Println("取消後再 stop:", stop())

	done, cancelDone := context.WithCancel(context.Background())
	cancelDone()
	ran := make(chan struct{})
	context.AfterFunc(done, func() { close(ran) })
	<-ran
	fmt.Println("已取消的 ctx 會立刻執行 f")
}
```

輸出：
```text
stop 成功: true
清理: 關閉連線、釋放暫存檔
取消後再 stop: false
已取消的 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` 可取消這個安排

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
