锁赋值给其他变量为什么会死锁呢?

``` package main import ( "fmt" "sync" ) type MyMutex struct { count int sync.Mutex } func main() { var mu MyMutex mu.Lock() var mu2 = mu mu.count++ mu.Unlock() mu2.Lock() mu2.count++ mu2.Unlock() fmt.Println(mu.count, mu2.count) } ``` 这段代码为什么会死锁呢? 赋值语句`var mu2 = mu` 执行后不应该是拷贝编程新的变量吗?
已邀请:

lifei6671 - PHPer

赞同来自: LiaoMessi

已经解决了,原来锁拷贝会将锁的状态也拷贝走。
```
// A RWMutex must not be copied after first use.
//
// If a goroutine holds a RWMutex for reading and another goroutine might
// call Lock, no goroutine should expect to be able to acquire a read lock
// until the initial read lock is released. In particular, this prohibits
// recursive read locking. This is to ensure that the lock eventually becomes
// available; a blocked Lock call excludes new readers from acquiring the
// lock.
```
加锁了 那你还怎么拷贝,改成下面这样就可以了
```go
package main
import (
"fmt"
"sync"
)
type MyMutex struct {
count int
sync.Mutex
}
func main() {
var mu MyMutex
mu.Lock()
mu.count++
mu.Unlock()
var mu2 = mu
mu2.Lock()
mu2.count++
mu2.Unlock()
fmt.Println(mu.count, mu2.count)
}
```

要回复问题请先登录注册