# 競態條件

多個 goroutine 同時讀寫同一份資料時會出什麼錯，以及怎麼用 `-race` 把它抓出來。

## 什麼是資料競爭

想像兩個人共用一本記帳本，各自「看一眼目前金額、心算加一、寫回去」。如果兩人同時看到 100，各自寫回 101，帳本就少記了一筆。

程式裡也一樣。**資料競爭（data race）** 的定義是：

- 兩個以上的 goroutine 存取同一個記憶體位置
- 其中至少一個是寫入
- 這些存取之間沒有任何同步（鎖、channel、原子操作等）

發生資料競爭時，結果不只是「數字算錯」而已。Go 的[記憶體模型](/sync-memory-model)明講：有資料競爭的程式，行為沒有保證。每次執行都可能不同，換一台機器、換一個 Go 版本也可能不同。

### 兩個以上 goroutine 同時寫同一個變數

下面的程式開 1000 個 [goroutine](/concurrency-goroutines)，每個把 `count` 加 1000 次。理論上最後應該是 1,000,000。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	count := 0
	var wg sync.WaitGroup
	for range 1000 {
		wg.Go(func() {
			for range 1000 {
				count++
			}
		})
	}
	wg.Wait()
	fmt.Println("count =", count)
}
```

輸出（每次結果可能不同，以下是其中一次的結果）：
```text
count = 278296
```

`wg.Go` 用來等所有 goroutine 結束，細節見 [WaitGroup 與 Once](/sync-once-waitgroup)。這裡的重點是：每次執行印出的數字都可能不一樣，而且幾乎一定小於 1,000,000。

### count++ 其實是三個步驟

`count++` 看起來是一行，實際上 CPU 要做三件事：

| 步驟 | 動作 |
| --- | --- |
| 1. 讀取 | 把 `count` 目前的值讀進暫存器 |
| 2. 計算 | 暫存器裡的值加 1 |
| 3. 寫回 | 把結果寫回 `count` |

兩個 goroutine 的步驟交錯時，就會有一次加法被蓋掉。下面在單一 goroutine 裡手動模擬這個交錯順序，讓你看清楚「少算」是怎麼發生的。

範例：
```go
package main

import "fmt"

func main() {
	count := 0

	a := count
	b := count

	a = a + 1
	b = b + 1

	count = a
	fmt.Println("A 寫回後:", count)
	count = b
	fmt.Println("B 寫回後:", count)

	fmt.Println("做了兩次加 1，結果卻是", count)
}
```

輸出：
```text
A 寫回後: 1
B 寫回後: 1
做了兩次加 1，結果卻是 1
```

A 和 B 都在對方寫回之前讀到 0，所以兩次加法只留下一次。

## 用 -race 偵測

資料競爭很難靠肉眼或測試結果發現：它可能在你的電腦上跑一千次都正常，上線後才出錯。Go 內建**競態偵測器（race detector）**，在編譯時加上 `-race` 旗標就會啟用：

| 指令 | 用途 |
| --- | --- |
| `go run -race .` | 執行程式並偵測 |
| `go test -race ./...` | 跑測試並偵測，最常用 |
| `go build -race` | 產生帶偵測功能的執行檔 |

偵測器只能抓到「這次執行實際發生」的競爭，沒跑到的程式路徑不會回報，所以要搭配涵蓋面夠廣的測試。開啟 `-race` 後程式會變慢、吃更多記憶體，適合開發與 CI，不適合正式環境長期開啟。

### go run -race 抓出競爭

範例：
```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	total := 0
	var wg sync.WaitGroup
	wg.Go(func() {
		total += 10
	})
	wg.Go(func() {
		total += 20
	})
	wg.Wait()
	fmt.Println("total =", total)
}
```

以 `go run -race -trimpath .` 執行（`-trimpath` 只是讓路徑變短）。

輸出（記憶體位址、goroutine 編號、讀寫順序與 `total` 的值每次可能不同，以下是其中一次的結果）：
```text
==================
WARNING: DATA RACE
Read at 0x00c00019e038 by goroutine 7:
  main.main.func1()
      example/main.go:12 +0x2c
  sync.(*WaitGroup).Go.func1()
      sync/waitgroup.go:258 +0x54

Previous write at 0x00c00019e038 by goroutine 8:
  main.main.func2()
      example/main.go:15 +0x3c
  sync.(*WaitGroup).Go.func1()
      sync/waitgroup.go:258 +0x54

Goroutine 7 (running) created at:
  sync.(*WaitGroup).Go()
      sync/waitgroup.go:238 +0x78
  main.main()
      example/main.go:11 +0xc0

Goroutine 8 (finished) created at:
  sync.(*WaitGroup).Go()
      sync/waitgroup.go:238 +0x78
  main.main()
      example/main.go:14 +0x124
==================
total = 30
Found 1 data race(s)
exit status 66
```

報告分成幾段：

- `Read at` 或 `Write at ... by goroutine N`：哪個 goroutine 在哪一行讀取或寫入
- `Previous write at ...`：與它衝突的另一次存取
- `Goroutine N (running) created at`：這些 goroutine 是在哪裡被建立的
- `Found 1 data race(s)`：總共幾處，偵測到競爭時程式結束碼是 66

照著行號回去找，就知道該保護哪個變數。

### 修正後再跑一次

最直接的修法是用[互斥鎖](/sync-mutex)把讀寫包起來。修好後再用 `-race` 跑，就不會有任何警告。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	total := 0
	var mu sync.Mutex
	var wg sync.WaitGroup
	wg.Go(func() {
		mu.Lock()
		total += 10
		mu.Unlock()
	})
	wg.Go(func() {
		mu.Lock()
		total += 20
		mu.Unlock()
	})
	wg.Wait()
	fmt.Println("total =", total)
}
```

以 `go run -race .` 執行。

輸出：
```text
total = 30
```

除了鎖，也可以用 [channel](/concurrency-channels) 把資料交給單一 goroutine 處理，或用[原子操作](/sync-atomic)。

注意：映射（map）不能同時寫入。多個 goroutine 同時寫同一個 map 時，執行期可能直接以 `fatal error: concurrent map writes` 終止程式，這種錯誤無法用 `recover` 攔下。

## 競態條件與資料競爭不一樣

**競態條件（race condition）** 是更廣的概念：程式的正確性取決於事件發生的先後順序。資料競爭是其中一種，但就算每次存取都有加鎖、沒有資料競爭，邏輯上仍可能出錯。

### 每一步都加鎖，仍然會出錯

典型例子是「先檢查、再動作（check-then-act）」：檢查餘額和扣款分成兩次加鎖，中間的空檔就可能被別人插隊。下面用 channel 固定兩個 goroutine 的執行順序，重現「兩人都檢查通過、接著都扣款」的情況。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Account struct {
	mu      sync.Mutex
	balance int
}

func (a *Account) Balance() int {
	a.mu.Lock()
	defer a.mu.Unlock()
	return a.balance
}

func (a *Account) Withdraw(n int) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.balance -= n
}

func main() {
	acc := &Account{balance: 100}
	checked := make(chan struct{})
	var wg sync.WaitGroup

	wg.Go(func() {
		if acc.Balance() >= 100 {
			<-checked
			acc.Withdraw(100)
		}
	})
	wg.Go(func() {
		if acc.Balance() >= 100 {
			checked <- struct{}{}
			acc.Withdraw(100)
		}
	})
	wg.Wait()
	fmt.Println("餘額:", acc.Balance())
}
```

輸出：
```text
餘額: -100
```

`-race` 不會回報這段程式，因為每次存取都有鎖保護；但餘額變成負數。解法是把「檢查」與「扣款」放進同一段鎖內，成為一個不可分割的動作：

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Account struct {
	mu      sync.Mutex
	balance int
}

func (a *Account) TryWithdraw(n int) bool {
	a.mu.Lock()
	defer a.mu.Unlock()
	if a.balance < n {
		return false
	}
	a.balance -= n
	return true
}

func main() {
	acc := &Account{balance: 100}
	results := make([]bool, 2)
	var wg sync.WaitGroup
	for i := range 2 {
		wg.Go(func() {
			results[i] = acc.TryWithdraw(100)
		})
	}
	wg.Wait()

	success := 0
	for _, ok := range results {
		if ok {
			success++
		}
	}
	fmt.Println("成功扣款次數:", success)
	fmt.Println("餘額:", acc.balance)
}
```

輸出：
```text
成功扣款次數: 1
餘額: 0
```

不管哪個 goroutine 先拿到鎖，都只會有一次成功，餘額固定是 0。

## 重點整理

- 資料競爭 = 多個 goroutine 存取同一位置、至少一個寫入、且沒有同步
- `count++` 是讀取、計算、寫回三步，交錯執行就會少算
- 用 `go test -race`、`go run -race` 偵測，只抓得到實際執行到的路徑
- 沒有資料競爭不代表沒有競態條件；「檢查」與「動作」要放在同一段鎖內
- 多個 goroutine 同時寫 map 會讓程式直接終止

## 資料來源

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