ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[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 } ```