# 取消與結束

啟動 goroutine 很簡單，讓它在該停的時候停下來才是難處，本頁說明 done channel、goroutine 洩漏的成因，以及如何避免。

## 為什麼要能取消

goroutine 沒有從外部強制終止的方法，Go 也不提供 goroutine 的 ID 讓你去「殺掉」它。goroutine 只會在自己的函式回傳時結束。

所以設計 goroutine 時要先回答兩個問題：

- 它什麼時候會結束？
- 呼叫端不再需要它時，怎麼通知它結束？

答不出來的 goroutine，很可能永遠不會結束。goroutine 的基礎見 [Goroutine](/concurrency-goroutines)。

## done channel

### 用關閉 channel 通知停止

慣用做法是準備一個 `done` channel（型別通常是 `chan struct{}`），goroutine 在 `select` 裡同時監聽它。要停止時 `close(done)`：已關閉的 channel 收值會立刻成功，`select` 就會走到停止的分支。`select` 用法見 [select](/concurrency-select)。

範例：
```go
package main

import (
	"fmt"
	"time"
)

func heartbeat(done <-chan struct{}, stopped chan<- string) {
	ticker := time.NewTicker(5 * time.Millisecond)
	defer ticker.Stop()
	beats := 0
	for {
		select {
		case <-ticker.C:
			beats++
		case <-done:
			stopped <- fmt.Sprint("heartbeat stopped, beats > 0: ", beats > 0)
			return
		}
	}
}

func main() {
	done := make(chan struct{})
	stopped := make(chan string)

	go heartbeat(done, stopped)
	time.Sleep(30 * time.Millisecond)

	close(done)
	fmt.Println(<-stopped)
}
```

輸出：
```text
heartbeat stopped, beats > 0: true
```

### close 是廣播

送一個值只能喚醒「一個」接收者；`close` 則會讓「所有」正在等待或之後才來等待的接收者都收到。所以通知多個 goroutine 一起停止時，用 `close` 而不是送值。

範例：
```go
package main

import (
	"fmt"
	"slices"
	"sync"
)

func main() {
	done := make(chan struct{})
	var mu sync.Mutex
	var stopped []string

	var wg sync.WaitGroup
	for _, name := range []string{"alpha", "beta", "gamma"} {
		wg.Go(func() {
			<-done
			mu.Lock()
			stopped = append(stopped, name)
			mu.Unlock()
		})
	}

	close(done)
	wg.Wait()

	slices.Sort(stopped)
	fmt.Println(stopped)
}
```

輸出：
```text
[alpha beta gamma]
```

注意：`done` 只能關閉一次，再關閉會 panic。多處都可能觸發停止時，用 `sync.Once` 包住 `close`，見 [WaitGroup 與 Once](/sync-once-waitgroup)。

## goroutine 洩漏

### 什麼是洩漏

goroutine 洩漏（goroutine leak）是指 goroutine 卡在某個永遠不會發生的操作上（等一個沒人送的 channel、送給一個沒人收的 channel），永遠不會結束。它佔用的記憶體和它引用的資料都無法回收；在伺服器裡每個請求漏一個，時間一久就會耗盡資源。

典型例子：同時問三個來源，只取最快的答案。用無緩衝 channel 的話，第一個送出後 `main` 就不再收，另外兩個 goroutine 永遠卡在送值。

範例：
```go
package main

import (
	"fmt"
	"runtime"
	"time"
)

func fastest(sources []string) string {
	ch := make(chan string)
	for _, s := range sources {
		go func() {
			ch <- "answer from " + s
		}()
	}
	<-ch
	return "got one answer"
}

func main() {
	fmt.Println(fastest([]string{"a", "b", "c"}))
	time.Sleep(50 * time.Millisecond)
	fmt.Println("goroutines still alive:", runtime.NumGoroutine())
}
```

輸出：
```text
got one answer
goroutines still alive: 3
```

除了 `main` 之外，還有 2 個 goroutine 永遠卡住，這就是洩漏。`time.Sleep` 只是讓已經送出的那一個有時間結束，好讓數字固定。

### 修正一：給足緩衝

如果每個 goroutine 只送一次值，把 channel 的容量設成 goroutine 的數量，送值就永遠不會卡住，送完就能結束；沒人收的值會隨 channel 一起被回收。

範例：
```go
package main

import (
	"fmt"
	"runtime"
	"time"
)

func fastest(sources []string) string {
	ch := make(chan string, len(sources))
	for _, s := range sources {
		go func() {
			ch <- "answer from " + s
		}()
	}
	<-ch
	return "got one answer"
}

func main() {
	fmt.Println(fastest([]string{"a", "b", "c"}))
	time.Sleep(50 * time.Millisecond)
	fmt.Println("goroutines still alive:", runtime.NumGoroutine())
}
```

輸出：
```text
got one answer
goroutines still alive: 1
```

### 修正二：送值時也監聽 done

產生器（不斷送值的 goroutine）沒辦法靠緩衝解決，因為它會一直送下去。這時送值要寫在 `select` 裡，同時監聽 `done`：消費端不要了就 `close(done)`，產生器就能從卡住的送值中脫身並結束。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

func naturals(done <-chan struct{}, wg *sync.WaitGroup) <-chan int {
	out := make(chan int)
	wg.Add(1)
	go func() {
		defer wg.Done()
		defer close(out)
		for i := 1; ; i++ {
			select {
			case out <- i:
			case <-done:
				return
			}
		}
	}()
	return out
}

func main() {
	done := make(chan struct{})
	var wg sync.WaitGroup

	nums := naturals(done, &wg)
	for range 3 {
		fmt.Println(<-nums)
	}

	close(done)
	wg.Wait()
	fmt.Println("generator exited")
}
```

輸出：
```text
1
2
3
generator exited
```

如果送值只寫 `out <- i`、不加 `select`，`main` 停止接收後產生器就會永遠卡在第 4 個值。

### 停止後等它真的結束

`close(done)` 只是「請求」停止，goroutine 可能還在收尾（寫檔、送出最後結果）。如果呼叫端接著就要釋放資源或結束程式，要等 goroutine 確實回傳。常見做法是把 done channel 和 `WaitGroup` 包成一個型別，提供 `Stop` 方法：關閉並等待。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Collector struct {
	in    chan int
	done  chan struct{}
	wg    sync.WaitGroup
	total int
}

func NewCollector() *Collector {
	c := &Collector{in: make(chan int), done: make(chan struct{})}
	c.wg.Go(c.run)
	return c
}

func (c *Collector) run() {
	for {
		select {
		case v := <-c.in:
			c.total += v
		case <-c.done:
			fmt.Println("flushing total:", c.total)
			return
		}
	}
}

func (c *Collector) Add(v int) { c.in <- v }

func (c *Collector) Stop() {
	close(c.done)
	c.wg.Wait()
}

func main() {
	c := NewCollector()
	for i := 1; i <= 5; i++ {
		c.Add(i)
	}
	c.Stop()
	fmt.Println("stopped")
}
```

輸出：
```text
flushing total: 15
stopped
```

`Stop` 回傳時保證 `run` 已經印出結果並結束，所以 `stopped` 一定在最後。

## 交給 context

### context 預告

done channel 是取消機制的原理。實務上標準庫用 `context.Context` 把它標準化：`ctx.Done()` 就是一個 done channel，`cancel()` 就是 `close`，另外還支援逾時與跨函式傳遞。`net/http`、`database/sql` 等套件都接受 `context`。完整說明見 [context 基礎](/context-basics) 與 [取消與逾時](/context-cancel-timeout)。

範例：
```go
package main

import (
	"context"
	"fmt"
)

func worker(ctx context.Context, result chan<- error) {
	<-ctx.Done()
	result <- ctx.Err()
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	result := make(chan error)

	go worker(ctx, result)
	cancel()

	fmt.Println("worker stopped:", <-result)
}
```

輸出：
```text
worker stopped: context canceled
```

## 避免洩漏的檢查清單

| 問題 | 檢查 |
| --- | --- |
| 送值會不會沒人收？ | 給足緩衝，或在 `select` 中同時監聽 done |
| 收值會不會沒人送？ | 送方是否一定會 `close`，或收方是否也監聽 done |
| `range ch` 會不會結束？ | 送方完成後有沒有 `close(ch)` |
| 呼叫端提早返回時呢？ | 有沒有 `close(done)` 或 `cancel()`，最好寫在 `defer` |
| 停止後要不要等？ | 需要時用 `WaitGroup` 等 goroutine 確實回傳 |

## 重點整理

- goroutine 無法從外部強制終止，只能通知它自己回傳
- 用 `close(done)` 通知停止；`close` 會喚醒所有等待者
- 卡在送值或收值、永遠不會結束的 goroutine 就是洩漏
- 單次送值給足緩衝；持續送值則在 `select` 中同時監聽 done
- 需要確定對方已結束時，`close(done)` 之後再 `wg.Wait()`
- 實務上用 `context` 取代手寫的 done channel

## 資料來源

- [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/)
