知识卡片
缩短取任务的持锁时间
将 receiver.lock().unwrap().recv() 写在示例的 while let 条件里,临时锁守卫会活到循环体末尾,job() 执行时仍占有队列锁,其他线程只能等待。改成独立 let message = receiver.lock().unwrap().recv(),接收结果已获得消息所有权,语句结束即可释放临时锁守卫。随后再匹配结果并执行任务,使锁只保护取活。
相关卡片 [[互斥锁守卫自动释放]]、[[共享唯一任务接收端]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 最终项目:构建多线程 Web 服务器 20 Final Project: Building a Multithreaded Web Server · 查看原书依据
The code in Listing 20-20 that uses let job = receiver.lock().unwrap().recv().unwrap(); works because with let, any temporary values used in the expression on the right-hand side of the equal sign are immediately dropped when the let statement ends. However, while let (and if let and match) does not drop temporary values until the end of the associated block.
参考来源
- 位置:《The Rust Programming Language(第2版)》第20章 最终项目:构建多线程 Web 服务器(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c20.xhtml`,块 0265)
- 结论依据:原文对照 let 语句结束和 while let 体结束两种临时值销毁时机,指出不同的并发结果。
- 原始内容:The code in Listing 20-20 that uses let job = receiver.lock().unwrap().recv().unwrap(); works because with let, any temporary values used in the expression on the right-hand side of the equal sign are immediately dropped when the let statement ends. However, while let (and if let and match) does not drop temporary values until the end of the associated block.