← 返回起始笔记位置

知识卡片

普通读书笔记卡 · 10346.a.3.h · 生成模型:未记录

共享唯一任务接收端

理解等级:中级

mpsc 的 Receiver 只有一个,直接在创建 Worker 的循环中移动它会让第一次移动后的各次循环失败。让 Worker 克隆 Arc>> 的 Arc,即共享同一个接收端。每次 recv 受互斥保护,每条消息只交给一个 Worker,多个任务的执行仍可并发。

相关卡片 [[多生产者共享接收端]]、[[跨线程共享可变数据]]、[[缩短取任务的持锁时间]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第20章 最终项目:构建多线程 Web 服务器(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c20.xhtml`,块 0236) - 结论依据:原文解释 Arc 提供共同所有权,Mutex 保证一次只有一个 Worker 从接收端取活。 - 原始内容:Recall the thread-safe smart pointers discussed in Chapter 16: to share ownership across multiple threads and allow the threads to mutate the value, we need to use Arc<Mutex<T>>. The Arc type will let multiple Worker instances own the receiver, and Mutex will ensure that only one Worker gets a job from the receiver at a time. Listing 20-18 shows the changes we need to make.