Rust mpsc :: Sender不能在线程之间共享?

Chr*_*ski 10 multithreading rust

我认为渠道的全部目的是在线程之间共享数据.我有这个代码,基于这个例子:

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

哪里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`
Run Code Online (Sandbox Code Playgroud)

我在哪里出错了我很困惑.除非我在错误的地方寻找并且我的问题实际上是我的用途let ctx = self;

blu*_*uss 17

发件人不能在线程之间共享,但可以发送!

它实现了特征,Send但没有Sync(同步:安全访问Sender跨线程的共享引用).

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

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

有趣的实施说明:该频道开始用作具有单个制作人的流.在第一次克隆发件人时,内部数据结构将升级为多生产者实现.


Aun*_*mag 6

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

了解更多信息: