首页 > 解决方案 > 为什么我不能将 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) 的构造函数创建一个通道,并在客户端发送发送,在后台线程中接收接收。我找不到这样做的方法。

标签: rust

解决方案


推荐阅读