【问题标题】:Rust mpsc::Sender cannot be shared between threads?Rust mpsc::Sender 不能在线程之间共享?
【发布时间】:2020-12-18 17:51:03
【问题描述】:

我认为通道的全部目的是在线程之间共享数据。我有这个代码,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;

【问题讨论】:

标签: multithreading rust


【解决方案1】:

发送者不能在线程之间共享,但可以发送

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

通道的设计旨在让您.clone() 发送者并将其作为值传递给线程(对于您拥有的每个线程)。您缺少线程闭包上的 move 关键字,该关键字指示闭包通过获取变量的所有权来捕获变量。

如果您必须在多个线程之间共享单个通道端点,则必须将其包装在互斥体中。 Mutex&lt;Sender&lt;T&gt;&gt; Sync + Send where T: Send.

有趣的实现说明:通道一开始是作为一个流使用的,它只有一个生产者。首次克隆发送者时,内部数据结构会升级为多生产者实现。

【讨论】:

    【解决方案2】:

    您可以使用标准库中的std::sync::mpsc::SyncSender。不同之处在于它实现了Sync trait,但如果在发送消息时内部缓冲区中没有空间,它可能会阻塞。

    更多信息:

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多