知识卡片
缩小守卫作用域缩短持锁
锁守卫的存在表示持锁,释放守卫会解锁。用小作用域包住真正需要保护的操作,可让后续日志、计算或其他调用在锁外运行,减少持锁时间。先确定哪些步骤必须共同受保护,再缩小范围;不能为快而拆开需要原子性的操作。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 2. Traits Item 11: Implement the Drop trait for RAII patterns · 查看原书依据
use blocks to restrict the scope of RAII items. This leads to slightly odd indentation, but it’s worth it for the added safety and lifetime precision: impl ThreadSafeInt { fn add_with_extras(&self, delta: i32) { // ... more code here that doesn't need the lock { let mut v = self.value.lock().unwrap(); *v += delta; } // ... more code here that doesn't need th
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第2章《Item 11: Implement the Drop trait for RAII patterns》(spine6;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch02.html;u067-ch02-014)。
- 结论依据:原文在“use blocks to restrict”附近的定义、例子或代码支撑本卡核心说明:锁守卫的存在表示持锁,释放守卫会解锁。边界按已读前提解释;示例未执行。
- 原始内容:use blocks to restrict the scope of RAII items. This leads to slightly odd indentation, but it’s worth it for the added safety and lifetime precision: impl ThreadSafeInt { fn add_with_extras(&self, delta: i32) { // ... more code here that doesn't need the lock { let mut v = self.value.lock().unwrap(); *v += delta; } // ... more code here that doesn't need th