競態條件

最後更新


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

什麼是資料競爭


想像兩個人共用一本記帳本,各自「看一眼目前金額、心算加一、寫回去」。如果兩人同時看到 100,各自寫回 101,帳本就少記了一筆。
程式裡也一樣。資料競爭(data race) 的定義是:
  • 兩個以上的 goroutine 存取同一個記憶體位置
  • 其中至少一個是寫入
  • 這些存取之間沒有任何同步(鎖、channel、原子操作等)

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

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


下面的程式開 1000 個 goroutine,每個把 count 加 1000 次。理論上最後應該是 1,000,000。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. count := 0
  8. var wg sync.WaitGroup
  9. for range 1000 {
  10. wg.Go(func() {
  11. for range 1000 {
  12. count++
  13. }
  14. })
  15. }
  16. wg.Wait()
  17. fmt.Println("count =", count)
  18. }

輸出(每次結果可能不同,以下是其中一次的結果):
  1. count = 278296

wg.Go 用來等所有 goroutine 結束,細節見 WaitGroup 與 Once。這裡的重點是:每次執行印出的數字都可能不一樣,而且幾乎一定小於 1,000,000。

count++ 其實是三個步驟


count++ 看起來是一行,實際上 CPU 要做三件事:
步驟動作
1. 讀取把 count 目前的值讀進暫存器
2. 計算暫存器裡的值加 1
3. 寫回把結果寫回 count

兩個 goroutine 的步驟交錯時,就會有一次加法被蓋掉。下面在單一 goroutine 裡手動模擬這個交錯順序,讓你看清楚「少算」是怎麼發生的。
範例:
  1. package main
  2. import "fmt"
  3. func main() {
  4. count := 0
  5. a := count
  6. b := count
  7. a = a + 1
  8. b = b + 1
  9. count = a
  10. fmt.Println("A 寫回後:", count)
  11. count = b
  12. fmt.Println("B 寫回後:", count)
  13. fmt.Println("做了兩次加 1,結果卻是", count)
  14. }

輸出:
  1. A 寫回後: 1
  2. B 寫回後: 1
  3. 做了兩次加 1,結果卻是 1

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

用 -race 偵測


資料競爭很難靠肉眼或測試結果發現:它可能在你的電腦上跑一千次都正常,上線後才出錯。Go 內建競態偵測器(race detector),在編譯時加上 -race 旗標就會啟用:
指令用途
go run -race .執行程式並偵測
go test -race ./...跑測試並偵測,最常用
go build -race產生帶偵測功能的執行檔

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

go run -race 抓出競爭


範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. total := 0
  8. var wg sync.WaitGroup
  9. wg.Go(func() {
  10. total += 10
  11. })
  12. wg.Go(func() {
  13. total += 20
  14. })
  15. wg.Wait()
  16. fmt.Println("total =", total)
  17. }

以 go run -race -trimpath . 執行(-trimpath 只是讓路徑變短)。
輸出(記憶體位址、goroutine 編號、讀寫順序與 total 的值每次可能不同,以下是其中一次的結果):
  1. ==================
  2. WARNING: DATA RACE
  3. Read at 0x00c00019e038 by goroutine 7:
  4. main.main.func1()
  5. example/main.go:12 +0x2c
  6. sync.(*WaitGroup).Go.func1()
  7. sync/waitgroup.go:258 +0x54
  8. Previous write at 0x00c00019e038 by goroutine 8:
  9. main.main.func2()
  10. example/main.go:15 +0x3c
  11. sync.(*WaitGroup).Go.func1()
  12. sync/waitgroup.go:258 +0x54
  13. Goroutine 7 (running) created at:
  14. sync.(*WaitGroup).Go()
  15. sync/waitgroup.go:238 +0x78
  16. main.main()
  17. example/main.go:11 +0xc0
  18. Goroutine 8 (finished) created at:
  19. sync.(*WaitGroup).Go()
  20. sync/waitgroup.go:238 +0x78
  21. main.main()
  22. example/main.go:14 +0x124
  23. ==================
  24. total = 30
  25. Found 1 data race(s)
  26. 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

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

修正後再跑一次


最直接的修法是用互斥鎖把讀寫包起來。修好後再用 -race 跑,就不會有任何警告。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. total := 0
  8. var mu sync.Mutex
  9. var wg sync.WaitGroup
  10. wg.Go(func() {
  11. mu.Lock()
  12. total += 10
  13. mu.Unlock()
  14. })
  15. wg.Go(func() {
  16. mu.Lock()
  17. total += 20
  18. mu.Unlock()
  19. })
  20. wg.Wait()
  21. fmt.Println("total =", total)
  22. }

以 go run -race . 執行。
輸出:
  1. total = 30

除了鎖,也可以用 channel 把資料交給單一 goroutine 處理,或用原子操作。
注意:映射(map)不能同時寫入。多個 goroutine 同時寫同一個 map 時,執行期可能直接以 fatal error: concurrent map writes 終止程式,這種錯誤無法用 recover 攔下。

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


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

每一步都加鎖,仍然會出錯


典型例子是「先檢查、再動作(check-then-act)」:檢查餘額和扣款分成兩次加鎖,中間的空檔就可能被別人插隊。下面用 channel 固定兩個 goroutine 的執行順序,重現「兩人都檢查通過、接著都扣款」的情況。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. type Account struct {
  7. mu sync.Mutex
  8. balance int
  9. }
  10. func (a *Account) Balance() int {
  11. a.mu.Lock()
  12. defer a.mu.Unlock()
  13. return a.balance
  14. }
  15. func (a *Account) Withdraw(n int) {
  16. a.mu.Lock()
  17. defer a.mu.Unlock()
  18. a.balance -= n
  19. }
  20. func main() {
  21. acc := &Account{balance: 100}
  22. checked := make(chan struct{})
  23. var wg sync.WaitGroup
  24. wg.Go(func() {
  25. if acc.Balance() >= 100 {
  26. <-checked
  27. acc.Withdraw(100)
  28. }
  29. })
  30. wg.Go(func() {
  31. if acc.Balance() >= 100 {
  32. checked <- struct{}{}
  33. acc.Withdraw(100)
  34. }
  35. })
  36. wg.Wait()
  37. fmt.Println("餘額:", acc.Balance())
  38. }

輸出:
  1. 餘額: -100

-race 不會回報這段程式,因為每次存取都有鎖保護;但餘額變成負數。解法是把「檢查」與「扣款」放進同一段鎖內,成為一個不可分割的動作:
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. type Account struct {
  7. mu sync.Mutex
  8. balance int
  9. }
  10. func (a *Account) TryWithdraw(n int) bool {
  11. a.mu.Lock()
  12. defer a.mu.Unlock()
  13. if a.balance < n {
  14. return false
  15. }
  16. a.balance -= n
  17. return true
  18. }
  19. func main() {
  20. acc := &Account{balance: 100}
  21. results := make([]bool, 2)
  22. var wg sync.WaitGroup
  23. for i := range 2 {
  24. wg.Go(func() {
  25. results[i] = acc.TryWithdraw(100)
  26. })
  27. }
  28. wg.Wait()
  29. success := 0
  30. for _, ok := range results {
  31. if ok {
  32. success++
  33. }
  34. }
  35. fmt.Println("成功扣款次數:", success)
  36. fmt.Println("餘額:", acc.balance)
  37. }

輸出:
  1. 成功扣款次數: 1
  2. 餘額: 0

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

重點整理


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

資料來源