知识卡片

普通读书笔记卡 · 6074.e.1.b.1

缩小守卫作用域缩短持锁

理解等级:中级

锁守卫的存在表示持锁,释放守卫会解锁。用小作用域包住真正需要保护的操作,可让后续日志、计算或其他调用在锁外运行,减少持锁时间。先确定哪些步骤必须共同受保护,再缩小范围;不能为快而拆开需要原子性的操作。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《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