互斥锁

最后更新于:2022-04-02 04:13:31

[TOC] ## go 没有重入锁的解决办法 bad ``` func Withdraw(amount int) bool { mu.Lock() defer mu.Unlock() Deposit(-amount) if Balance() < 0 { Deposit(amount) // 在已经上锁的情况下在调用Deposit会出现死锁 return false } return true } func Deposit(amount int) { mu.Lock() defer mu.Unlock() balance += amount } ``` good ``` //降低函数的颗粒度 func Withdraw(amount int) bool { mu.Lock() defer mu.Unlock() deposit(-amount) if balance < 0 { deposit(amount) return false // insufficient funds } return true } func Deposit(amount int) { mu.Lock() defer mu.Unlock() deposit(amount) } func Balance() int { mu.Lock() defer mu.Unlock() return balance } //拆成更小的函数 func deposit(amount int) { balance += amount } ```
';