# 恐慌：sync：互斥锁已被锁定

- **ID:** `go/mutex-copied-after-use`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

sync.Mutex 或其他同步原语在使用后被复制，导致锁状态被复制，使用副本时可能导致死锁或恐慌。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.20 | active | — | — |
| 1.21 | active | — | — |

## 解决方案

1. **** (98% 成功率)
   ```
   type SafeCounter struct {
    mu sync.Mutex
    v  int
}

func (c *SafeCounter) Inc() {
    c.mu.Lock()
    c.v++
    c.mu.Unlock()
}

// Always use *SafeCounter, never copy the struct.
   ```
2. **** (95% 成功率)
   ```
   type Counter struct {
    mu *sync.Mutex
    v  int
}

func NewCounter() *Counter {
    return &Counter{mu: &sync.Mutex{}}
}

func (c *Counter) Inc() {
    c.mu.Lock()
    c.v++
    c.mu.Unlock()
}
   ```

## 无效尝试

- **** — The panic will recur unpredictably; it's a fundamental design flaw. (100% 失败率)
- **** — Copying a mutex is illegal; it cannot be safely copied at all. (100% 失败率)
