# 互斥鎖

用 `sync.Mutex` 與 `sync.RWMutex` 保護共享資料，並掌握「鎖要包多大範圍」。

## 為什麼需要鎖

多個 goroutine 同時讀寫同一份資料會造成[資料競爭](/sync-race-conditions)。**互斥鎖（mutex，mutual exclusion）** 就像廁所門上的鎖：同一時間只有一個人能進去，其他人在門外排隊，等裡面的人出來（解鎖）才輪到下一個。

被鎖保護的那段程式稱為**臨界區（critical section）**。

| 型別 | 適用情境 |
| --- | --- |
| `sync.Mutex` | 一般情況，讀寫都只允許一個 goroutine |
| `sync.RWMutex` | 讀多寫少，允許多個讀者同時讀 |

兩者的零值都可以直接使用，不需要初始化。

## sync.Mutex

### Lock 與 Unlock

`Lock` 取得鎖，如果鎖已被別人拿走就會一直等；`Unlock` 釋放鎖，讓下一個等待者進來。

簽名：
```go
func (m *Mutex) Lock()
func (m *Mutex) Unlock()
```

範例：
```go
package main

import (
	"fmt"
	"sync"
)

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

輸出：
```text
count = 1000000
```

和[競態條件](/sync-race-conditions)頁那個每次結果都不同的版本相比，加上鎖之後每次都是 1,000,000。

注意：對沒有上鎖的 `Mutex` 呼叫 `Unlock` 會讓程式以 `fatal error: sync: unlock of unlocked mutex` 終止，無法 `recover`。

### 用 defer 確保解鎖

函式有多個 `return`，或中途可能 panic 時，很容易漏掉 `Unlock`。慣用寫法是 `Lock` 之後立刻 `defer mu.Unlock()`（見 [defer](/func-defer)），函式結束時一定會解鎖。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Inventory struct {
	mu    sync.Mutex
	stock map[string]int
}

func (inv *Inventory) Take(item string, n int) error {
	inv.mu.Lock()
	defer inv.mu.Unlock()

	if inv.stock[item] < n {
		return fmt.Errorf("%s 庫存不足：剩 %d，要 %d", item, inv.stock[item], n)
	}
	inv.stock[item] -= n
	return nil
}

func main() {
	inv := &Inventory{stock: map[string]int{"apple": 5}}
	fmt.Println(inv.Take("apple", 3))
	fmt.Println(inv.Take("apple", 3))
	fmt.Println("剩餘:", inv.stock["apple"])
}
```

輸出：
```text
<nil>
apple 庫存不足：剩 2，要 3
剩餘: 2
```

第二次呼叫提前 `return` 了錯誤，`defer` 仍然會把鎖解開。

### 把鎖和資料放在同一個結構體

慣例是把 `mu` 放在它要保護的欄位正上方，方法都用[指標接收者](/methods-pointer-receiver)。這樣讀程式的人一眼就知道哪些欄位歸這把鎖管。

範例：
```go
package main

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

type Visits struct {
	mu     sync.Mutex
	counts map[string]int
}

func NewVisits() *Visits {
	return &Visits{counts: make(map[string]int)}
}

func (v *Visits) Hit(page string) {
	v.mu.Lock()
	defer v.mu.Unlock()
	v.counts[page]++
}

func (v *Visits) Snapshot() map[string]int {
	v.mu.Lock()
	defer v.mu.Unlock()
	out := make(map[string]int, len(v.counts))
	for k, n := range v.counts {
		out[k] = n
	}
	return out
}

func main() {
	v := NewVisits()
	pages := []string{"/home", "/about", "/home", "/blog", "/home", "/blog"}
	var wg sync.WaitGroup
	for _, p := range pages {
		wg.Go(func() {
			v.Hit(p)
		})
	}
	wg.Wait()

	snap := v.Snapshot()
	keys := make([]string, 0, len(snap))
	for k := range snap {
		keys = append(keys, k)
	}
	slices.Sort(keys)
	for _, k := range keys {
		fmt.Println(k, snap[k])
	}
}
```

輸出：
```text
/about 1
/blog 2
/home 3
```

`Snapshot` 回傳的是複本，呼叫端之後怎麼讀都不需要再鎖。如果直接回傳 `v.counts`，外面的人就能繞過鎖存取內部的映射。

注意：`Mutex` 在第一次使用後不能被複製。如果用值接收者，或把含有 `Mutex` 的結構體以值傳遞，每份複本都有自己的鎖，保護就失效了。`go vet` 的 copylocks 檢查會抓出這種錯誤。

### Mutex 不可重入

**重入（reentrant）** 指同一個執行者在持有鎖時再次取得同一把鎖。Go 的 `Mutex` 不支援：已經 `Lock` 的 goroutine 再呼叫一次 `Lock`，會永遠卡住。下面用 `TryLock`（嘗試上鎖，拿不到就立刻回傳 `false`）示範這件事。

簽名：
```go
func (m *Mutex) TryLock() bool
```

範例：
```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	fmt.Println("第一次 TryLock:", mu.TryLock())
	fmt.Println("持有中再 TryLock:", mu.TryLock())
	mu.Unlock()
	fmt.Println("解鎖後 TryLock:", mu.TryLock())
	mu.Unlock()
}
```

輸出：
```text
第一次 TryLock: true
持有中再 TryLock: false
解鎖後 TryLock: true
```

`TryLock` 一般程式很少需要，這裡只用來觀察鎖的狀態。實務上避免重入的做法是：公開方法負責上鎖，內部再呼叫一個「假設已持有鎖」的私有方法，不在持有鎖時呼叫另一個也會上鎖的公開方法。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Cart struct {
	mu    sync.Mutex
	items []int
}

func (c *Cart) Add(price int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items = append(c.items, price)
}

func (c *Cart) Total() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.totalLocked()
}

func (c *Cart) Checkout() (int, int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	total := c.totalLocked()
	n := len(c.items)
	c.items = nil
	return n, total
}

func (c *Cart) totalLocked() int {
	sum := 0
	for _, p := range c.items {
		sum += p
	}
	return sum
}

func main() {
	c := &Cart{}
	c.Add(120)
	c.Add(80)
	fmt.Println("小計:", c.Total())
	n, total := c.Checkout()
	fmt.Println("結帳:", n, "件，共", total)
	fmt.Println("結帳後小計:", c.Total())
}
```

輸出：
```text
小計: 200
結帳: 2 件，共 200
結帳後小計: 0
```

如果 `Checkout` 裡直接呼叫 `c.Total()`，就會在持有鎖時再上一次鎖，程式卡死。

## sync.RWMutex

### RLock 與 RUnlock

**讀寫鎖（read-write mutex）** 把存取分成兩種：

| 方法 | 意義 | 可同時持有 |
| --- | --- | --- |
| `RLock` ／ `RUnlock` | 讀鎖 | 多個讀者可以同時持有 |
| `Lock` ／ `Unlock` | 寫鎖 | 只能有一個，且此時不能有任何讀者 |

適合「讀很多、寫很少」的資料，例如設定、快取。

簽名：
```go
func (rw *RWMutex) RLock()
func (rw *RWMutex) RUnlock()
func (rw *RWMutex) Lock()
func (rw *RWMutex) Unlock()
```

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Cache struct {
	mu   sync.RWMutex
	data map[string]string
}

func (c *Cache) Get(key string) (string, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	v, ok := c.data[key]
	return v, ok
}

func (c *Cache) Set(key, value string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.data[key] = value
}

func main() {
	c := &Cache{data: make(map[string]string)}
	c.Set("lang", "Go")

	results := make([]string, 5)
	var wg sync.WaitGroup
	for i := range 5 {
		wg.Go(func() {
			v, _ := c.Get("lang")
			results[i] = fmt.Sprintf("reader %d 讀到 %s", i, v)
		})
	}
	wg.Wait()
	for _, r := range results {
		fmt.Println(r)
	}

	_, ok := c.Get("missing")
	fmt.Println("missing 存在嗎:", ok)
}
```

輸出：
```text
reader 0 讀到 Go
reader 1 讀到 Go
reader 2 讀到 Go
reader 3 讀到 Go
reader 4 讀到 Go
missing 存在嗎: false
```

注意：`RWMutex` 本身的管理成本比 `Mutex` 高。如果讀寫比例差不多，或臨界區很短，用 `Mutex` 通常一樣快甚至更快；先用 `Mutex`，量測後確定有讀取瓶頸再換。另外，持有讀鎖時不能再要求寫鎖（`RLock` 後呼叫 `Lock`），會永遠卡住。

## 鎖的範圍

### 臨界區越小越好

持有鎖的時間越長，其他 goroutine 排隊越久。原則是：**只把讀寫共享資料的那幾行放進鎖內**，計算、I/O、網路呼叫這類耗時工作放在鎖外。

範例：
```go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type Index struct {
	mu    sync.Mutex
	words map[string]int
}

func countWords(text string) map[string]int {
	local := make(map[string]int)
	for _, w := range strings.Fields(strings.ToLower(text)) {
		local[w]++
	}
	return local
}

func (idx *Index) Merge(local map[string]int) {
	idx.mu.Lock()
	defer idx.mu.Unlock()
	for w, n := range local {
		idx.words[w] += n
	}
}

func main() {
	docs := []string{
		"Go is simple",
		"Go is fast",
		"simple is good",
	}
	idx := &Index{words: make(map[string]int)}
	var wg sync.WaitGroup
	for _, d := range docs {
		wg.Go(func() {
			local := countWords(d)
			idx.Merge(local)
		})
	}
	wg.Wait()

	for _, w := range []string{"go", "is", "simple", "fast", "good"} {
		fmt.Printf("%-6s %d\n", w, idx.words[w])
	}
}
```

輸出：
```text
go     2
is     3
simple 2
fast   1
good   1
```

切字、轉小寫在各自的 goroutine 裡並行完成，只有最後合併進共享映射時才上鎖。

### 一組相關的修改要在同一段鎖內

範圍也不能太小。如果兩個欄位必須一起保持一致（例如「轉出」與「轉入」），就要在同一次上鎖內一起改，否則別人可能在中間看到不一致的狀態。

範例：
```go
package main

import (
	"fmt"
	"sync"
)

type Bank struct {
	mu       sync.Mutex
	accounts map[string]int
}

func (b *Bank) Transfer(from, to string, amount int) bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.accounts[from] < amount {
		return false
	}
	b.accounts[from] -= amount
	b.accounts[to] += amount
	return true
}

func (b *Bank) Total() int {
	b.mu.Lock()
	defer b.mu.Unlock()
	sum := 0
	for _, v := range b.accounts {
		sum += v
	}
	return sum
}

func main() {
	b := &Bank{accounts: map[string]int{"alice": 500, "bob": 500}}
	var wg sync.WaitGroup
	for range 100 {
		wg.Go(func() { b.Transfer("alice", "bob", 7) })
		wg.Go(func() { b.Transfer("bob", "alice", 3) })
	}
	wg.Wait()
	fmt.Println("總額:", b.Total())
}
```

輸出：
```text
總額: 1000
```

不管轉帳以什麼順序發生，總額永遠是 1000，因為扣款和入帳不會被拆開。

## 重點整理

- `Mutex` 的零值即可用；`Lock` 後緊接 `defer Unlock()` 最不容易出錯
- 把鎖和它保護的欄位放在同一個結構體，用指標接收者，不要複製含鎖的值
- Go 的鎖不可重入；用「公開方法上鎖、私有方法假設已上鎖」的分工避免卡死
- 讀多寫少才考慮 `RWMutex`，先用 `Mutex`
- 臨界區只包住共享資料的讀寫，但必須一起改的欄位要放在同一段鎖內

## 資料來源

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