我认为通道的全部目的是在线程之间共享数据.我有这个密码,based on this example:

let tx_thread = tx.clone();
let ctx = self;
thread::spawn(|| {
    ...
    let result = ctx.method()
    tx_thread.send((String::from(result), someOtherString)).unwrap();
})

其中txmpsc::Sender<(String, String)>

error[E0277]: the trait bound `std::sync::mpsc::Sender<(std::string::String, std::string::String)>: std::marker::Sync` is not satisfied
   --> src/my_module/my_file.rs:137:9
    |
137 |         thread::spawn(|| {
    |         ^^^^^^^^^^^^^
    |
    = note: `std::sync::mpsc::Sender<(std::string::String, std::string::String)>` cannot be shared between threads safely
    = note: required because of the requirements on the impl of `std::marker::Send` for `&std::sync::mpsc::Sender<(std::string::String, std::string::String)>`
    = note: required because it appears within the type `[closure@src/my_module/my_file.rs:137:23: 153:10 res:&&str, ctx:&&my_module::my_submodule::Reader, tx_thread:&std::sync::mpsc::Sender<(std::string::String, std::string::String)>]`
    = note: required by `std::thread::spawn`

我不知道哪里出了错.除非我找错了地方,而我的问题实际上是我对let ctx = self;的使用?

推荐答案

发送器在线程之间不能为shared,但可以为sent

它实现了trait Send而不是Sync(Sync:跨线程安全地访问Sender的共享引用).

通道的设计意图是将发送方发送.clone()个,并将其作为一个值传递给一个线程(对于每个线程).线程闭包中缺少move关键字,该关键字指示闭包通过获取变量的所有权来捕获变量.

如果必须在多个线程之间共享单个通道端点,则必须将其包装在互斥对象中.Mutex<Sender<T>> is Sync + Send where T: Send.

有趣的实现说明:该频道开始用作流,其中只有一个生产者.第一次克隆发送方时,内部数据 struct 将升级为多生产者实现.

Rust相关问答推荐

为什么迭代器上的`. map(...)`的返回类型如此复杂?

Rust kill std::processs::child

在HashMap中插入Vacant条目的可变借位问题

为什么`Vec i64`的和不知道是`Option i64`?

使用模块中的所有模块,但不包括特定模块

什么时候铁 rust FFI边界上的panic 是未定义的行为?

将PathBuf转换为字符串

在我的Cargo 中,当我在建筑物中使用时,找不到我可以在产品包中使用的 crate .r我如何解决这个问题?

使用关联类型重写时特征的实现冲突

Cargo.toml:如何有条件地启用依赖项功能?

`UnsafeCell` 在没有锁定的情况下跨线程共享 - 这可能会导致 UB,对吗?

`use` 和 `crate` 关键字在 Rust 项目中效果不佳

仅当函数写为闭包时才会出现生命周期错误

rust 中不同类型的工厂函数

Rust 引用元组和引用元组

在空表达式语句中移动的值

以下打印数组每个元素的 Rust 代码有什么问题?

如何制作具有关联类型的特征的类型擦除版本?

如何在不设置精度的情况下打印浮点数时保持尾随零?

在 Rust 中组合特征的不同方法是否等效?