rust - 为什么我不能将 mpsc::Receiver 交给生成的线程?
问题描述
这是无法编译的代码。
use std::{
sync::{
mpsc::{self, Receiver, Sender},
Arc,
},
thread,
};
struct S1 {
rx: Receiver<i32>,
}
pub struct S2 {
inner: Arc<S1>,
tx: Sender<i32>,
}
impl S2 {
pub fn new() -> S2 {
let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
let st1 = S1 { rx };
let st2 = S2 {
tx,
inner: Arc::new(st1),
};
st2
}
pub fn start(&mut self) {
let inner = &self.inner.clone();
let _jh = thread::spawn(move || loop {
inner.rx.recv().unwrap();
});
}
}
fn main() {}
S2
是客户端可见的代码,S1
是后端线程维护的内部状态。这似乎是一个常见的 Rust 习语。
这是错误:
error[E0277]: `std::sync::mpsc::Receiver<i32>` cannot be shared between threads safely
--> src/main.rs:31:19
|
31 | let _jh = thread::spawn(move || loop {
| ^^^^^^^^^^^^^ `std::sync::mpsc::Receiver<i32>` cannot be shared between threads safely
|
= help: within `S1`, the trait `std::marker::Sync` is not implemented for `std::sync::mpsc::Receiver<i32>`
= note: required because it appears within the type `S1`
= note: required because of the requirements on the impl of `std::marker::Sync` for `std::sync::Arc<S1>`
= note: required because of the requirements on the impl of `std::marker::Send` for `&std::sync::Arc<S1>`
= note: required because it appears within the type `[closure@src/main.rs:31:33: 33:10 inner:&std::sync::Arc<S1>]`
这不是为什么在将包含 Arc 的 self 移动到新线程时出现“不满足同步”的错误?. 我不在乎我有Arc
没有。我只希望我的客户端可见事物 ( S2
) 的构造函数创建一个通道,并在客户端发送发送,在后台线程中接收接收。我找不到这样做的方法。
解决方案
推荐阅读
- google-cloud-dataflow - 在更新 Dataflow 管道时强制更新 SideInput
- office-js - Excel 插件自定义函数与现有 com 插件 UDF 兼容
- sql-server - 通过 XML 转换为 varbinary 的 SQL 字符串与 nvarchar 不同
- dialogflow-es - 无法找到错误对话流履行的来源
- python - 有人能解释一下 root 函数在这个快速联合实现中是如何工作的吗?
- get - 如何获得使用popen传递的“GET /”请求的响应与底层openssl通信
- c# - 使用 azure 自定义活动运行将 DBF 文件转换为 CSV 的 c# 可执行文件
- ios - 在 SwiftUI 的导航栏中设置图像和标题
- reactjs - 反应材料表:如何覆盖材料表中的标题样式?
- javascript - 为什么我的 JQuery 脚本没有用正确的 iframe 替换数据属性?