-
Notifications
You must be signed in to change notification settings - Fork 469
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
对于加锁和解锁操作为什么不使用defer #34
Comments
没什么不同吧。。。 |
defer的话,不管下面逻辑怎样都会执行,相当于try finally 解锁,防止lock后逻辑出错,锁一直被占着 |
不知道你贴这个意义是什么,,这里面原话是
何来性能损耗这中说法? 而且
这句话也不对吧, 少看点八股文,,多看看实际场景。 |
这三行代码,一共就三种情况 锁住 从 map 中获取 value 成功 用不用 defer 无影响 |
我的意思不是针对某一个场景,我的意思是unlock放defer一方面可读行好,一方面是可以防止忘记unlock操作,以及中间代码执行错误unlock没有执行 |
如果你的函数有 300 行,defer 会可读性更好,这函数就三行,用不用 defer 没区别。除非你的屏幕只能显示两行代码。具体情况具体分析。 defer只是个语法糖,并不是代码风格的强制要求。可以推荐这种写法,但行数少的时候不这么写也不算错。 |
啊这,这个问题没必要专门提个issue吧,有点离谱哎 |
func (b *Bucket) Room(rid int) (room *Room) {
b.cLock.RLock()
room, _ = b.rooms[rid]
b.cLock.RUnlock()
return
}
为何不写作
func (b *Bucket) Room(rid int) (room *Room) {
b.cLock.RLock()
defer b.cLock.RUnlock()
room, _ = b.rooms[rid]
return
}
The text was updated successfully, but these errors were encountered: