Rust 如何获取 Arc 的内容

Rust How to Get Contents of Arc

我有一个包含 TcpStream 的 class - 不能保证 TcpStream 在那里 - 所以我最初使用 Option 但发现 Arc 使用线程安全 - 因为我是 运行 异步任务 - 这可能会导致一些线程问题。所以我结束了我的 Arc<TcpStream> 但在获取数据时遇到问题...

#[derive(Debug, Clone)]
enum ConnectionError {
    ConnectError(usize),
    SendError(usize),
}

#[derive(Debug, Clone)]
struct Connection {
    stream: Arc<TcpStream>,
    loc: usize,
}

impl Connection {
    async fn connect(loc:usize) -> Result<Connection, ConnectionError> {
        println!("Connecting");
        
        let stream = TcpStream::connect("3.77.107.247:86").await.map_err(|_| ConnectionError::ConnectError(loc))?;
        //stream.write_all(b"Hello World\n").await;

        Ok( Connection2 {
            stream: Arc::new(stream),
            loc: loc,
            }
        )
    }
    async fn Send(mut connection: Connection, string: String) -> Result<Connection2, ConnectionError> {
        println!("Count: {},", Arc::weak_count(&connection.stream));
        if let Some(x) = Arc::get_mut(&mut connection.stream) {
            x.write_all(b"HELLO").await.map_err(|_| ConnectionError::SendError(connection.loc))?;
        }
        else {
            println!("Unable to send message");
        }
        Ok( connection )
    }
}

我总是以意外的输出结束:

Unable to send message thread 'tokio-runtime-worker' panicked at 'called Option::unwrap() on a None value', src\main.rs:292:58 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

这表明我的 Arc get_mut 为空...

我已经打印出如图所示的 Weak count,但输出为 0。

有指导吗?

I have a class that contains a TcpStream - that TcpStream isn't guaranteed to be there - so I originally used Option but found that Arc uses thread safety - and since I am running async tasks - it is possible that this could cause some threading issues. So I wrapped up my Arc but am having issues getting the data...

那是……可能完全是错误的解决方案?而且两者甚至不能互换,

I have a class that contains a TcpStream - that TcpStream isn't guaranteed to be there

位没了? Arc 做不到,它总是包含一些东西。

Option是线程安全的,一次只能存在于一个线程中。 Arc 是线程安全的,可以在线程间共享。按照您的设计方式,您可以在不同的线程中有多个 Connection 共享相同的底层 tcp 流,这听起来是个糟糕的主意。

此外,Arc 不能直接变异(除非它特别具有 1 的强计数,显然这里不是这种情况),相反你需要使用某种线程安全的“内部可变性” " 容器可以从不可变引用中产生可变引用,通常是 Mutex or an RWLock.

这里我看不到 ArcOption:

的意义
  • 在多个 Connection 之间直接共享一个 TcpStream 听起来不是个好主意,某种池化或多路复用可能没问题,但我想要非常明确和有意的支持对于它,不仅仅是在管道中发送垃圾并希望它以可接受的状态从另一端出来,交错的消息听起来像是灾难的根源。

  • Arc不能为空,所以

    I have a class that contains a TcpStream - that TcpStream isn't guaranteed to be there

    选项的理由毫无意义。