首页 > 解决方案 > Rust:如何使用 Arc 在新生成的线程中使用特征中定义的方法?

问题描述

所以我试图在一个特征中定义一个方法,它会产生一个线程并利用另一个特征方法,但我有点坚持如何从 Arc<...> 中“解包”它:

use std::sync::Arc;
use std::sync::Mutex;
use websocket::{Message, WebSocketResult};


trait Sender<S>
where
    S: Into<Message<'static>> + Send,
{
    fn send_once(&mut self, message: S) -> WebSocketResult<()>;
    fn send_in_thread(&mut self, sleep_interval: time::Duration) -> WebSocketResult<()> {
        let self_copy = Arc::new(Mutex::new(self)).clone();
        let thread_join_handle = thread::spawn(move || self_copy.send_once(message));
        thread_join_handle.join().unwrap()
    }
}

我得到的错误是:

no method named `send_once` found for struct `std::sync::Arc<std::sync::Mutex<&mut Self>>` in the current scope

method not found in `std::sync::Arc<std::sync::Mutex<&mut Self>>`

这是公平的,我没有在这个包装器类型上定义这样的方法,但是我怎样才能以最短的方式摆脱这种情况呢?或者,最惯用的方式?我使用 Arc 是因为以前Self cannot be sent between threads safely如果我不使用它,我就有了。

标签: rust

解决方案


您需要先锁定互斥体以获得 a MutexGuard,然后才能对其调用方法:

let thread_join_handle = thread::spawn(move || self_copy
    .lock()
    .unwrap()
    .send_once(message));

推荐阅读